How to filter based on clipboard in Excel using VB

2019-08-18 04:52发布

问题:

I work with a bunch of people in my department and always share my code with them so you'll be helping me and my coworkers as well!

Using the macro recorder I have created this code to filter the column I want filtered, but I need to change the code to filter it based on what ever is on the clipboard (what ever cell I pressed Ctrl+C on previously). I pressed Ctrl+C while recording the macro but it didn't record those button presses, it only pasted what was in my clipboard at the time into the macro.

Sub Filter()

    ActiveSheet.Range("$A$1:$V$12955").AutoFilter Field:=2, Criteria1:= _
        "Clipboard"

End Sub

回答1:

This is one of the First Projects That I did in Excel. I will explain How my code is working, then you can manipulate this according to your need.

Youtube Link on How to Use it

After Pasting the code in your Personal Macro, Create a Shortcut on the Quick Access ToolBar for this Macro.

Then All you need to do is, Apply Autofilter on the Range you want to Filter, Copy the Cell or the Range of Cells that contains the value you want to filter, and select the header of the column on which you want to apply this Filter. Press the Created Shortcut.

It will work on the Single Cell Also, So you don't need to amend it. Just follow the Instructions Above.

Here Is the Code:

Sub filtrr()
'
    Dim i As Integer
    Dim Test As String
    Dim clipboard As MSForms.DataObject
    Set clipboard = New MSForms.DataObject

    clipboard.GetFromClipboard
    Test = clipboard.GetText

    Test = Replace(Test, Chr(13), "-")
    Test = Trim(WorksheetFunction.Clean(Test))

    Dim ab() As String

    ab = Split(Test, "-")

    ReDim Preserve ab(UBound(ab) - 1)

    ActiveSheet.UsedRange.AutoFilter Field:=Selection.Column, Criteria1:=ab, Operator:= _
        xlFilterValues


End Sub

In your case it's only One cell that contains value, but this code is a life saver if you want to filter like 50 values in a table of thousands of values.