Detect Autofilter changes

后端 未结 2 1580
花落未央
花落未央 2021-01-16 00:40

I am looking to detect any changes in an autofilter on a specific table, for the purpose of forcing a UDF that does some simple arithmetic on the table entries that are curr

2条回答
  •  再見小時候
    2021-01-16 00:53

    How to trigger Worksheet Calculation following AutoFilter changes while in Manual Calculation

    As we know changes to the AutoFilter selection cannot be automatically detected, as these changes do not trigger any Workbook Event or Worksheet Event. Therefore, only option available is to have the user triggering worksheet calculations with an action i.e. Cell Selection Change, Right Click, Double Click, etc; or just by pressing [F9]; which is the preferable action as there is nothing else involved and it's the way it's designed to work.

    Nevertheless, at the user request, I'm providing this VBA code that although needs to be initiated by user's action, this action can be done immediately after the AutoFilter change is selected, just by Double Clicking.

    The DoubleClick can be unrestricted (double clicking any cell in the worksheet) by using this code:

    Private Sub Worksheet_BeforeDoubleClick(ByVal rTrg As Range, blCancel As Boolean)
        rTrg.Worksheet.Calculate
    End Sub
    

    or setting up to three types of restrictions:

    1. Any cell of the Table

    2. The Header of the Table

    3. The Body of the Table

    Use this code to restrict the DoubleClick area: Currently the code is set to restriction type 1, use variable bRType to change it to the preferred type. This code assumed the name of the Table is Table1 (change as required)

    Private Sub Worksheet_BeforeDoubleClick(ByVal rTrg As Range, blCancel As Boolean)
    Dim ObjLst As ListObject, rTbl As Range, bRType As Byte
    
        Rem Set Restriction Type
        Rem 1: DoubleCliking any cell of the Table - Default
        Rem 2: DoubleCliking any cell of the Table Header
        Rem 3: DoubleCliking any cell of the Table Body
        bRType = 1
    
        With rTrg
            Set ObjLst = .Worksheet.ListObjects("Table1")
    
            Select Case bRType
            Case 2:     Set rTbl = ObjLst.HeaderRowRange
            Case 3:     Set rTbl = ObjLst.DataBodyRange
            Case Else:  Set rTbl = ObjLst.Range
            End Select
    
            If Not (Intersect(.Cells, rTbl) Is Nothing) Then
                .Worksheet.Calculate
                blCancel = True
            End If
        End With
    End Sub
    

    Both procedures are Worksheet Events, therefore ensure that the one that you decide to implement goes into the module of the worksheet holding the Table. (do not change the name of the procedures)

提交回复
热议问题