我的代码中有一个公共跟踪子,如下所示:
Public Sub ResetFilters(ByRef tbl As ListObject)
With tbl
'// If Filter Arrows are OFF - turns them on
'// If Filter Arrows are ON - turns them off and resets filter
.Range.AutoFilter
'// Always turns filter arrows to on and sorts table by first field
.Range.AutoFilter Field:=1
End With
End Sub
你可以看到我使用Excel表(vba中的ListObjects
)所以我将引用传递给sub,它应该将表重置为未过滤状态。它在使用Excel 2007的PC上运行良好,但在Mac上的Excel 2011上失败:
对象'范围'的方法'自动过滤'失败
Excel 2011 VBA Reference的以下链接显示AutoFilter
对象的Range
方法,它与我在Excel 2007 VBA参考的参考中看到的相匹配。
所以有人能看出为什么会失败吗?
答案 0 :(得分:3)
我无法让ListObject.ShowAutoFilter
解决方法为我工作,特别是因为我不仅需要关闭自动过滤器,而且还需要在代码完成后以编程方式还原过滤器。
我在Mac上进行了宏观录制时发现有点麻烦,发现即使Range.AutoFilter
抛出错误Selection.AutoFilter
也没有。所以我只能选择我想要过滤的范围,然后将我的过滤器应用到选择中。
ws.Range(currentFiltRange).Select
Selection.AutoFilter
如果您需要保留用户的选择,您也可以轻松恢复它,这是我完整的子例程,用于保存autoFilter状态,运行您自己的代码,然后恢复自动过滤器状态,它可以在PC和Mac上运行。
Private Sub saveAndRestoreAutoFilterPCandMAC()
Application.ScreenUpdating = False
'START SAVING AUTOFILTER STATE
Dim ws As Worksheet
Dim filterArray()
Dim currentFiltRange As String
Dim col As Integer
Dim usingAutoFilter As Boolean
Dim userSelection As String
usingAutoFilter = False
Set ws = ActiveSheet
'Capture AutoFilter settings
If ws.AutoFilterMode = True Then
With ws.AutoFilter
currentFiltRange = .Range.Address
If ws.FilterMode = True Then
usingAutoFilter = True
With .Filters
ReDim filterArray(1 To .count, 1 To 3)
For col = 1 To .count
With .Item(col)
If .On Then
filterArray(col, 1) = .Criteria1
If .Operator Then
filterArray(col, 2) = .Operator
If .Operator = xlAnd Or .Operator = xlOr Then
filterArray(col, 3) = .Criteria2
End If
End If
End If
End With
Next col
End With
End If
End With
End If
'END SAVING AUTOFILTER STATE
'Remove AutoFilter
ws.AutoFilterMode = False
'Start Your code here
'End of your code
'START RESTORE FILTER SETTINGS
If Not currentFiltRange = "" Then
userSelection = Selection.Address
ws.Range(currentFiltRange).Select
Selection.AutoFilter
If usingAutoFilter Then
For col = 1 To UBound(filterArray(), 1)
If Not IsEmpty(filterArray(col, 1)) Then
If filterArray(col, 2) Then
'check if Criteria2 exists and needs to be populated
If filterArray(col, 2) = xlAnd Or filterArray(col, 2) = xlOr Then
ws.Range(currentFiltRange).Select
Selection.AutoFilter Field:=col, _
Criteria1:=filterArray(col, 1), _
Operator:=filterArray(col, 2), _
Criteria2:=filterArray(col, 3)
Else
ws.Range(currentFiltRange).Select
Selection.AutoFilter Field:=col, _
Criteria1:=filterArray(col, 1), _
Operator:=filterArray(col, 2)
End If
Else
ws.Range(currentFiltRange).Select
Selection.AutoFilter Field:=col, _
Criteria1:=filterArray(col, 1)
End If
End If
Next col
End If
End If
ws.Range(userSelection).select
'END RESTORE FILTER SETTINGS
Application.ScreenUpdating = True
End Sub
答案 1 :(得分:0)
似乎没有很多人跳过这个问题......无论如何,如果有其他人感兴趣,我想我找到了一个使用ListObject.ShowAutoFilter
属性的解决方法。它是一个读/写布尔属性,当关闭时,它将重置ListObject中的过滤器。它还可以在PC上使用Excel 2011 for Mac和Excel 2007(以及2010年)。