How to retrieve the sql code from an Excel 2007 PivotTable

前端 未结 1 2032
你的背包
你的背包 2021-01-24 05:53

I have a pivot table, which I want to recreate programatically through python. Is there way to retrieve the current sql code of the pivot table for me to use it in python?

相关标签:
1条回答
  • 2021-01-24 06:17

    I wrote this recently. It might work for you. It attempts to copy pivot cache and/or query table data for the active workbook to the clipboard. It's surrounded by On Error Resume Next so if it doesn't find a particular piece of data it keeps going:

    Sub Copy_Connection_Info_To_Clipboard()
    
    Dim ptCache As Excel.PivotCache
    Dim qtQueryTable As Excel.QueryTable
    Dim strPtCacheInfo As String
    Dim strQueryTableInfo As String
    Dim ws As Excel.Worksheet
    Dim strConnectionInfo As String
    Dim doConnectionInfo As DataObject
    
    On Error Resume Next
    For Each ptCache In ActiveWorkbook.PivotCaches
        With ptCache
            strPtCacheInfo = _
            strPtCacheInfo _
            & "PivotCache #" & "Index: " & .Index & vbCrLf & vbCrLf _
                             & "SourceDataFile: " & .SourceDataFile & vbCrLf & vbCrLf _
                             & "CommandText: " & .CommandText & vbCrLf & vbCrLf _
                             & "SourceConnectionFile: " & .SourceConnectionFile & vbCrLf & vbCrLf _
                             & "Connection: " & .Connection & vbCrLf & vbCrLf
        End With
    Next ptCache
    If strPtCacheInfo <> "" Then
        strPtCacheInfo = "PivotCache Info" & vbCrLf & vbCrLf & strPtCacheInfo
    End If
    
    For Each ws In ActiveWorkbook.Worksheets
        If ws.QueryTables.Count > 0 Then
            strQueryTableInfo = "Worksheet: " & ws.Name & vbCrLf
            For Each qtQueryTable In ActiveSheet.QueryTables
                With qtQueryTable
                    strQueryTableInfo = _
                    strQueryTableInfo _
                    & "QueryTable Name: " & .Name & vbCrLf & vbCrLf _
                    & .SourceDataFile & vbCrLf & vbCrLf _
                    & .CommandText & vbCrLf & vbCrLf _
                    & .SourceConnectionFile & vbCrLf & vbCrLf _
                    & .Connection & vbCrLf & vbCrLf
                End With
            Next qtQueryTable
        End If
    Next ws
    If strQueryTableInfo <> "" Then
        strQueryTableInfo = "Query Table Info" & vbCrLf & strQueryTableInfo
    End If
    
    strConnectionInfo = strPtCacheInfo & strQueryTableInfo
    If strConnectionInfo <> "" Then
        Set doConnectionInfo = New DataObject
        doConnectionInfo.SetText strConnectionInfo
        doConnectionInfo.PutInClipboard
    End If
    
    End Sub
    
    0 讨论(0)
提交回复
热议问题