Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel Filtering and Copying in VBA

Tags:

excel

filter

vba

I'm working on a VBA script that pulls a range of dates from Access, then filters the data and creates a chart based on the filtered data. The filtered data will be going to a separate sheet where the chart will be pulling its data from . I can get data out of Access with a SQL statement, but my AutoFilter in Excel is erroring out. Here is what I have...

Sheet3.Range("F4:F500").AutoFilter(, "Riveter 01").Copy Destination:=Sheet2.Range("A5")

It gives an app-defined or object-defined error and I can't figure out why. Is this the proper way or is there an easier way?

PS: This filter will happen with 22 unique machines so I was planning on running a loop for each machine. If that is not the fastest or proper way please let me know.

like image 406
Grant Avatar asked Dec 19 '12 15:12

Grant


1 Answers

You need to split this into two parts. Filter and then copy/ paste. See below:

With Sheet3
    .AutoFilterMode = False
    With .Range("F4:F500")
        .AutoFilter Field:=1, Criteria1:="Riveter 01"
        .SpecialCells(xlCellTypeVisible).Copy Destination:=Sheet2.Range("A5")
    End With
End With

to remove the filter:

On Error Resume Next
    Sheet3.ShowAllData
On Error GoTo 0

On Error Resume Next is for when there is no filter present to skip the error. Please note the use of Sheet3 and Sheet2 for those looking for a generic solution.

like image 68
InContext Avatar answered Oct 07 '22 23:10

InContext