获取Worksheet_change事件以自动执行宏

时间:2013-03-13 04:16:10

标签: excel excel-vba vba

我有一个宏(ApplyFilter),根据我在另一个工作表(Grand Totals)上输入单元格B1的日期过滤掉许多工作表。该宏是:

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

当我手动执行此宏时,它会按原样执行和过滤。但是,当我从另一个子域调用此宏时:

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

我得到一个“宏”窗口,提供可用的宏列表。我可以选择“ApplyFilter”宏并单击“运行”,宏将根据需要执行并过滤工作表。

我发现很多引用从子内部自动执行宏,但没有引用“宏”窗口,我现在必须从中选择要运行的宏。相反,当我在“Grand Totals”工作表的单元格B1中输入日期并按Enter键时,sub worksheet_change(ByVal Target As Range)应自动调用“ApplyFilter”并将日期过滤器应用于许多工作表。

我创建了一个按钮并使用Button_Click调用“ApplyFilter”,一切都很顺利。但是,输入日期似乎更直观,然后按Enter执行宏。我可以忍受Button_Click方法,但我首先想要学习VBA,而我只是顽固地想要学习如何使它工作,而且我不想仅仅为了什么工作而解决。

1 个答案:

答案 0 :(得分:2)

图纸代码必须位于Grand Totals

  • 右键点击Grand Totals表格标签
  • View Code
  • 确保将以下代码粘贴在此处
  • 返回Excel

Grand Totals Sheet Code

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

更高效的过滤代码

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