【发布时间】:2016-08-03 00:18:54
【问题描述】:
我有一个包含 13 张工作表的 excel 工作簿(一年中每个月一张 + 一张主工作表),每张工作表都有一个相同的员工统计数据表。员工统计表以其对应的月份命名,并具有相同的列标题。 我在主工作表上有一个仪表板,其中包含从其他表格中提取的图表。
我想创建一个搜索框,让您可以一次过滤各自工作表中的所有表格
这是我无法弄清楚的代码行。我正在尝试使过滤器范围引用多个表。
Set DataRange = sheets.ListObjects("January""February""March").Range
是否有任何方法可以对搜索框进行编码以引用多个工作表中的多个表?我需要确定工作表名称和表名称。我不知道该怎么做
作为参考,一月是工作表中标题为“一月”的表格。
这是我使用的完整代码:
Sub SearchBox()
Dim dict as Object
Set dict = CreateObject("Scripting.Dictionary")
Dim i as Long
For 1 = 3 to 14
Set dict(i) = Worksheets(i).ListObjects(1).Range
Dim myButton As OptionButton
Dim MyVal As Long
Dim ButtonName As String
Dim sht As Worksheet
Dim myField As Long
Dim DataRange As Range
Dim mySearch As Variant
'Load Sheet into A Variable
Set sht = ActiveSheet
'Unfilter Data (if necessary)
On Error Resume Next
sht.ShowAllData
On Error GoTo 0
'Filtered Data Range (include column heading cells)
dict(i).Autofilter_
Field:=myField,_
Criteria1:="=*" & mySearch & "*", _
Operator:=xlAnd
Next
'Retrieve User's Search Input
mySearch = sht.Shapes("StaffLookUp").TextFrame.Characters.Text 'Control Form
'Loop Through Option Buttons
For Each myButton In ActiveSheet.OptionButtons
If myButton.Value = 1 Then
ButtonName = myButton.Text
Exit For
End If
Next myButton
'Determine Filter Field
On Error GoTo HeadingNotFound
myField = Application.WorksheetFunction.Match(ButtonName, DataRange.Rows(1), 0)
On Error GoTo 0
'Filter Data
DataRange.AutoFilter _
Field:=myField, _
Criteria1:="=*" & mySearch & "*", _
Operator:=xlAnd
'Clear Search Field
sht.Shapes("UserSearch").TextFrame.Characters.Text = "" 'Control Form
Exit Sub
'ERROR HANDLERS
HeadingNotFound:
MsgBox "The column heading [" & ButtonName & "] was not found in cells " & DataRange.Rows(1).Address & ". " & _
vbNewLine & "Please check for possible typos.", vbCritical, "Header Name Not Found!"
End Sub
【问题讨论】: