[vb.net][Visual Studio] 强制枢轴 table 到 refresh/recalculate

[vb.net][Visual Studio] Force pivot table to refresh/recalculate

我正在尝试创建供开发人员使用的功能区。我要添加的项目之一是 sheet 重新计算需要多少时间,因此我可以比较进行一些更改前后的情况。 在目标 sheet 我有一个支点 table.

如何强制 sheet 重新计算?直到现在我尝试过的一切都没有任何作用。

Private Sub btlCalculate_Click(sender As Object, e As EventArgs) Handles btlCalculate.Click
        'https://codesnippets.fesslersoft.de/measure-execution-time-of-a-action/

        'Dim time0 = Now()
        Dim WB As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
        Dim WS As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet

        With ListView1
            With .Items.Add(WB.Name)
                .SubItems.Add(WS.Name)
            End With
        End With

        Dim watch = Stopwatch.StartNew()

        With Globals.ThisAddIn.Application
            .CalculateFull()
            '.Calculate()
        End With
        watch.Stop()

        Dim intervalToMs = watch.Elapsed.TotalMilliseconds
        'Dim time1 = Now()
        'Dim interval As TimeSpan = time1 - time0
        'Dim intervalToMs = interval.TotalMilliseconds

        With ListView1
            With .Items.Add(WS.Name)
                .SubItems.Add(intervalToMs)
            End With
        End With
    End Sub

我能够解决这个问题。它似乎正在计算 sheet(我使用 Randbetween 函数进行测试,但它没有计算 Pivot Table。我错过了 pivot table 不计算的事实sheet 重新计算时自动。

   Private Sub btlCalculate_Click(sender As Object, e As EventArgs) Handles btlCalculate.Click
        'https://codesnippets.fesslersoft.de/measure-execution-time-of-a-action/

        'Dim time0 = Now()
        Dim WB As Excel.Workbook = Globals.ThisAddIn.Application.ActiveWorkbook
        Dim WS As Excel.Worksheet = Globals.ThisAddIn.Application.ActiveSheet
        Dim AVG As Double, total As Double, I
        Dim PT As Excel.PivotTable

        Dim watch = Stopwatch.StartNew()

        On Error Resume Next

        If chkPivot.Checked Then
            For Each PT In WS.PivotTables
                PT.RefreshTable()
            Next
        Else
            WS.Calculate()
        End If


        watch.Stop()

        Dim intervalToMs = watch.Elapsed.TotalMilliseconds
        'Dim time1 = Now()
        'Dim interval As TimeSpan = time1 - time0
        'Dim intervalToMs = interval.TotalMilliseconds

        With Me.DataGridView1
            Dim rowI As String() = New String() { .RowCount, WS.Name, intervalToMs, TimeOfDay.ToString("HH:mm:ss")}
            .Rows.Add(rowI)

            For I = 0 To .Rows.Count - 2
                total += CDbl(.Rows(I).Cells(2).Value)
            Next

            AVG = total / (.Rows.Count - 1)
        End With

        txtAvg.Text = AVG

        On Error GoTo 0
    End Sub