VBA Excel-刷新数据透视表/功能查询

时间:2019-11-27 23:43:41

标签: excel vba

我正在尝试先刷新Power Query然后再刷新数据透视表(运行该数据),并且当我使用F8逐步执行代码时,我可以使其正常工作,但是在运行宏时它将无法工作

有什么想法吗?

谢谢!

Sub Test()

Dim WB As Workbook
Dim pt As PivotTable
Set WB = ThisWorkbook
Set pt = ActiveSheet.PivotTables("PivotTable1")

'Refresh Power Queries & Pivot Tables
ThisWorkbook.RefreshAll
WB.Worksheets("By Customer Pivot").Activate
pt.RefreshTable


End Sub

1 个答案:

答案 0 :(得分:0)

这是刷新所有电源查询的方法。

Sub RefreshAllPQ_Queries()

    Dim Connection As WorkbookConnection
    Dim lTest As Long

    On Error Resume Next

    For Each cn In ThisWorkbook.Connections

        lTest = InStr(1, cn.OLEDBConnection.Connection, _
                "Provider=Microsoft.Mashup.OleDb.1")

        If Err.Number <> 0 Then

            Err.Clear

            Exit For

        End If

    If lTest > 0 Then cn.Refresh

    Next cn


End Sub

这是刷新刷新表的方法。

Sub RefreshPivotTable()


    Dim wb As Workbook
    Dim ws As Worksheet
    Dim strWS As String
    Dim strPT As String

    strWS = "Invoice"
    strPT = "pt_Invoice"
    Set wb = ThisWorkbook
    Set ws = wb.Worksheets(strWS)

    ws.PivotTables(strPT).PivotCache.Refresh

    Set ws = Nothing
    Set wb = Nothing
    strWS = vbNullString
    strPT = vbNullString

End Sub