sourcetip

[ Refresh ]또는 [Refresh All]버튼을 누른 후 매크로를 호출하는 방법

fileupload 2023. 4. 18. 23:15
반응형

[ Refresh ]또는 [Refresh All]버튼을 누른 후 매크로를 호출하는 방법

최종적으로 워크북을 갱신한 후 매크로를 실행하고 싶습니다.특히 Excel의 Data 탭에 있는 Refresh 버튼을 사용합니다.

당분간은 [Refresh]버튼을 누르면 [BeforeRefresh]또는 [AfterRefresh QueryTable]이벤트를 기동하는 것만으로 충분합니다.

Microsoft Dev Center Web 사이트의 문서와 더불어, 제가 읽은 관련 투고는 다음과 같습니다.

제가 가지고 있는 것은 다음과 같습니다.

Under Class Modules (qtclass)

Option Explicit

Private WithEvents qt As Excel.QueryTable

Private Sub qt_AfterRefresh(ByVal Success As Boolean)

    MsgBox "qt_AfterRefresh called sucessfully."
    If Success = True Then
        Call Module2.SlicePivTbl
        MsgBox "If called succesfully."
    End If

End Sub

Private Sub qt_BeforeRefresh(Cancel As Boolean)
    MsgBox "qt_BeforeRefresh called."
End Sub

ThisWorkbook 모듈 아래

Private Sub Workbook_Open()

    Dim qtevent As qtclass
    Dim qt As QueryTable
    Set qt = ThisWorkbook.Worksheets("Data-Fund").ListObjects(1).QueryTable
    Set qtevent = New qtclass

End Sub

특정 워크시트에서 두 번째 코드 블록의 변형을 시도해 보았지만, 아직 효과가 있는 것을 찾지 못했습니다.워크시트 모듈에서 문제의 QueryTable을 어둡게 해야 합니까?

쿼리 테이블을 클래스 인스턴스에 실제로 연결하지 않았습니다.수정된 QT클래스

Option Explicit

Private WithEvents qt As Excel.QueryTable
Public Property Set HookedTable(q As Excel.QueryTable)
    Set qt = q
End Property

Private Sub qt_AfterRefresh(ByVal Success As Boolean)

    MsgBox "qt_AfterRefresh called sucessfully."
    If Success = True Then
        Call Module2.SlicePivTbl
        MsgBox "If called succesfully."
    End If

End Sub

Private Sub qt_BeforeRefresh(Cancel As Boolean)
    MsgBox "qt_BeforeRefresh called."
End Sub

새로운 ThisWorkbook 코드:

Dim qtevent As qtclass
Private Sub Workbook_Open()

    Set qtevent = New qtclass
    Set qtevent.HookedTable = ThisWorkbook.Worksheets("Data-Fund").ListObjects(1).QueryTable

End Sub

이것은 매우 밀접하게 관련되어 있습니다.클래스에서 이벤트를 발생시키고 Qtevent 변수 WithEvents를 선언하는 경우 더 재사용할 수 있습니다.

출처 : https://www.excelandaccess.com/create-beforeafter-query-update-events/

클래스: 주의:클래스 이름 =clsQuery

Option Explicit

Public WithEvents MyQuery As QueryTable

Private Sub MyQuery_AfterRefresh(ByVal Success As Boolean)
 If Success Then
  Debug.Print "After ReFresh"
 End If
End Sub

Private Sub MyQuery_BeforeRefresh(Cancel As Boolean)
 Debug.Print "Before ReFresh"
End Sub

모듈:

Option Explicit
Dim colQueries As New Collection
Sub InitializeQueries()

Dim clsQ As clsQuery
Dim WS As Worksheet
Dim QT As QueryTable

For Each WS In ThisWorkbook.Worksheets
 For Each QT In WS.QueryTables
  Set clsQ = New clsQuery
  Set clsQ.MyQuery = QT
  colQueries.Add clsQ
 Next QT
Next WS

End Sub

이 워크북이벤트:

Private Sub Workbook_Open()
 
 Call InitializeQueries
 
End Sub

언급URL : https://stackoverflow.com/questions/26983053/how-to-call-macro-after-refresh-or-refresh-all-button-pressed

반응형