如何使用 VBA 保存并重新应用当前过滤器?
在 Excel 2007 VBA 中,我正在尝试
- 保存用户在当前工作表上拥有的任何过滤器
- 清除过滤器
- “做事”
- 重新应用已保存的过滤器
最佳答案
为了防止链接失效,这里是代码(感谢原作者):
适用于Excel 2010,只需删除标记的注释行即可。
Sub ReDoAutoFilter()
Dim w As Worksheet
Dim filterArray()
Dim currentFiltRange As String
Dim col As Integer
Set w = ActiveSheet
' Capture AutoFilter settings
With w.AutoFilter
currentFiltRange = .Range.Address
With .Filters
ReDim filterArray(1 To .Count, 1 To 3)
For f = 1 To .Count
With .Item(f)
If .On Then
filterArray(f, 1) = .Criteria1
If .Operator Then
filterArray(f, 2) = .Operator
filterArray(f, 3) = .Criteria2 'simply delete this line to make it work in Excel 2010
End If
End If
End With
Next f
End With
End With
'Remove AutoFilter
w.AutoFilterMode = False
' Your code here
' Restore Filter settings
For col = 1 To UBound(filterArray(), 1)
If Not IsEmpty(filterArray(col, 1)) Then
If filterArray(col, 2) Then
w.Range(currentFiltRange).AutoFilter field:=col, _
Criteria1:=filterArray(col, 1), _
Operator:=filterArray(col, 2), _
Criteria2:=filterArray(col, 3)
Else
w.Range(currentFiltRange).AutoFilter field:=col, _
Criteria1:=filterArray(col, 1)
End If
End If
Next col
End Sub
关于excel - 在 Excel VBA 中,如何保存/恢复用户定义的过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9489126/