我需要在活动工作表中找到一个表(一个工作表只有一个表),并找到该表中的第一列和最后一列,然后从第一列和最后一列中删除自动过滤器。
目前我正在这样做:-问题是我必须手动输入字段值,因为工作表的名称以及表格的名称都会更改
Private Sub Worksheet_Activate()
' Select middle cell
ActiveSheet.Range("$A$1").Select
' Remove autofilter from first column in the table
With Range("$A$2")
.AutoFilter Field:=1, VisibleDropDown:=False
End With
' Remove autofilter from last column in the table
With Range("$Q$2")
.AutoFilter Field:=17, VisibleDropDown:=False
End With
End Sub
Workbook_SheetActivate
)ThisWorkbook
模块中。Option Explicit
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
Dim tbl As ListObject
On Error Resume Next
Set tbl = Sh.ListObjects(1)
On Error GoTo 0
If Not tbl Is Nothing Then
With tbl.Range
.Columns(1).AutoFilter 1, VisibleDropdown:=False
.Columns(.Columns.Count).AutoFilter .Columns.Count, _
VisibleDropdown:=False
End With
End If
End Sub
编辑:排除工作表
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
' To exclude charts (kind of covered with 'On Error' statement).
'If sh.Type <> xlWorksheet Then Exit Sub
Dim Exceptions As Variant: Exceptions = Array("Sheet1", "Sheet2")
' To exclude the sheets in the list:
If IsError(Application.Match(Sh.Name, Exceptions, 0)) Then
' To restrict to the sheets in the list:
'If IsNumeric(Application.Match(Sh.Name, Exceptions, 0)) Then
Dim tbl As ListObject
On Error Resume Next
Set tbl = Sh.ListObjects(1)
On Error GoTo 0
If Not tbl Is Nothing Then
With tbl.Range
.Columns(1).AutoFilter 1, VisibleDropdown:=False
.Columns(.Columns.Count).AutoFilter .Columns.Count, _
VisibleDropdown:=False
End With
End If
End If
End Sub
Private Sub Worksheet_Activate()
With Me.ListObjects
If .Count = 1 Then
With .Item(1).Range
.AutoFilter Field:=1
.AutoFilter Field:=.Columns.Count
End With
End If
End With
End Sub