以下是一個示例的VBA動態篩選代碼:
Sub DynamicFilter()
Dim ws As Worksheet
Dim rng As Range
Dim criteriaRange As Range
Dim filterRange As Range
Dim filteredRange As Range
' 設置工作表和篩選范圍
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set rng = ws.Range("A1:E10")
' 設置篩選條件范圍并輸入篩選條件
Set criteriaRange = ws.Range("G1:G2")
criteriaRange.Cells(1).Value = "Apple"
criteriaRange.Cells(2).Value = "Orange"
' 設置要篩選的范圍
Set filterRange = rng
' 清除之前的篩選結果
filterRange.AutoFilter
' 應用篩選條件并獲取篩選結果
filterRange.AutoFilter Field:=1, Criteria1:=criteriaRange.Cells(1).Value, Operator:=xlOr, Criteria2:=criteriaRange.Cells(2).Value
Set filteredRange = filterRange.SpecialCells(xlCellTypeVisible)
' 在篩選結果中進行其他操作,例如復制到其他位置
filteredRange.Copy ws.Range("H1")
' 清除篩選
filterRange.AutoFilter
End Sub
上述代碼會在Sheet1的A1:E10范圍內進行動態篩選,篩選條件為G1和G2單元格的值(“Apple"和"Orange”),篩選結果將復制到H1單元格。