阅读量:5
以下是一个示例的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单元格。