简体   繁体   中英

Is it possible to specify dynamic range in auto filter syntax?

I have written below code to apply auto filter. Code is working fine. However I have specified static range, here: *Range("A1", **"M"** & lastRow).AutoFilter* . Is there a way to replace "M" with last existing column number in sheet2. I have calculated last existing column *myCol = rngFound.Column - 1* . But not sure how to use it. Please help !!!

My Code:

Sub testfilter1()
Dim lastRow As Long
Dim myCol As Long
Dim rngFound As Range

ThisWorkbook.Sheets("sheet2").Activate

 lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row

        Set rngFound = ActiveSheet.Rows(1).Find(What:="", LookIn:=xlValues, LookAt:=xlWhole, _
            SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)

            myCol = rngFound.Column - 1 ' this will give last used column

Rows("1:1").Select
Selection.AutoFilter
ActiveSheet.Range("A1", "M" & lastRow).AutoFilter Field:=4, Criteria1:="*somename*"

End Sub

You could use Cells() within Range() :

...Range(Cells(1,1),Cells(lastRow,myCol))...

Cells(1,1) is the cell A1 . The format is Cells([row],[column])

Edit: Just realized you could also use Range("A1",Cells(lastRow,myCol)) . Personally, if I use Cells() I do it in both places in Range() , but that's personal preference and this other way should work for you too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM