我正在尝试创建一个函数,如果单元格包含某个值,则在单元格范围内插入一个过滤器
这是我的代码:
Sub FilterFunc()
Dim i As Long, lastCol As Long
Dim rng As Range, cell As Range
Dim wSheet As Worksheet
Set wSheet = Worksheets("Sheet1")
'find the last column in row one
lastCol = wSheet.Cells(1, Columns.Count).End(xlToRight).Column 'xlToLeft
'set range from A1 to last column
Set rng = wSheet.Range(wSheet.Cells(1, 1), wSheet.Cells(1, lastCol))
'Outline the autofilter field hierarchy
i = 1
For Each cell In rng
If cell.Value <> "" Then
wSheet.Cells(cell.Row + 2, cell.Column).AutoFilter Field:=cell.Column, Criteria1:=cell.Value
End If
Next cell
End Sub
当执行如下代码时:
wSheet.Cells(cell.Row + 2, cell.Column).AutoFilter Field:=cell.Column, Criteria1:=cell.Value
它返回运行时错误:1004 Range 类的自动过滤方法失败
这可能有点愚蠢,但我想弄清楚我哪里做错了,我试过在 stackoverflow 上查找,甚至提出了一个问题,但我没有太多运气