获取Worksheet_change事件自动执行macros

我有一个macros(ApplyFilter),它可以根据我在另一个工作表(Grand Totals)中input到单元格B1的date来筛选许多工作表。 那个macros是:

Sub ApplyFilter() 'Filters all worksheets except worksheet1 for date entered into _ 'Grand Totals!B1 Dim WS_Count As Integer Dim I As Integer Dim FilterRange As Variant FilterRange = Range("'Grand Totals'!B1") ' Set WS_Count equal to the number of worksheets in the active ' workbook. WS_Count = ActiveWorkbook.Worksheets.Count ' Begin the loop. For I = 2 To WS_Count Sheets(I).Select ActiveSheet.AutoFilterMode = False 'Remove any existing filters Worksheets(I).Range("A2").AutoFilter Field:=1, Criteria1:=Range("'Grand Totals'!B1").Text Next I Sheet1.Activate End Sub 

当我手动执行这个macros,它会执行和过滤,因为它应该。 但是,当我从另一个子调用这个macros:

 Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Me.Range("B1")) Is Nothing Then _ Call ApplyFilter End Sub 

我得到一个“macros”窗口,提供了可用的macros列表。 我可以select“ApplyFilter”macros,然后单击“运行”,macros将按照我的需要执行和过滤工作表。

我发现许多引用自动执行从一个子内的macros,但没有引用“macros”窗口,我现在必须selectmacros运行。 相反,当我在“总计”工作表B1单元格中input一个date,然后按回车时,sub worksheet_change(ByVal Target As Range)应自动调用“ApplyFilter”并将date筛选器应用于许多工作表。

我创build了一个button,并使用Button_Click来调用“ApplyFilter”,一切都很好。 但是,inputdate似乎更直观,然后按Enter执行macros。 我可以忍受Button_Click方法,但是我首先想学习VBA,而且我只是固执己见,想要学习如何使它工作,我不想只为了什么工作。

表格代码必须在Grand Totals表格中

  • 右键单击您的Grand Totals表选项卡
  • View Code
  • 确保下面的代码被粘贴在这里
  • alt f11回到Excel

总计表代码

 Sub Worksheet_Change(ByVal Target As Range) If Not Intersect(Target, Me.Range("B1")) Is Nothing Then Call ApplyFilter End Sub 

更高效的filter代码

 Sub ApplyFilter() Dim ws As Worksheet For Each ws In ActiveWorkbook.Sheets If ws.Name <> "Grand Totals" Then ws.AutoFilterMode = False ws.Range("A2").AutoFilter Field:=1, Criteria1:=Range("'Grand Totals'!B1").Text End If Next End Sub