Reputation: 61
I need a code that will find the last column with values and filter that column by multiple criteria. Here’s what I’ve come up with so far.
Dim LastCol As Integer
With ActiveSheet
LastCol = .Cells(1, .Columns.Count).End(xlToLeft).column
End With
With ActiveSheet
AutoFilter Field:=1, Criteria1:=Array("Age*", "Weight*"),
Operator:=xlFilterValues
Upvotes: 1
Views: 890
Reputation: 10139
First, I would recommend that you declare your worksheet object. I turned your LastCol
into a function.
Try this:
Option Explicit
Function lastCol(ByVal ws As Worksheet, Optional ByVal row As Variant = 1) As Long
With ws
lastCol = .Cells(row, .Columns.Count).End(xlToLeft).Column
End With
End Function
Sub test()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets(1)
With ws.UsedRange
.AutoFilter Field:=lastCol(ws), Criteria1:=Array("Age*", "Weight*"), Operator:=xlFilterValues
End With
End Sub
Using ActiveSheet
, ActiveCell
, .Select
, .Selection
, .Activate
, etc is rarely good for your code. In minimal cases it's useful, but the vast majority of the time it can be a debugging nightmare.
Upvotes: 1