Changing pivot table external data source path wit

2019-03-04 07:40发布

问题:

I'm working on a project in MS Excel where I have several Pivot Tables that read data from a tab-delimited text file with column names in the first row (in the same directory as the Excel file) using the Microsoft Text Driver. I've run into a problem where when I copy the text and Excel files to a new directory and try to refresh the data it says it can't find the text files. Unfortunately there seems to be no way to tell Excel I want the paths to the text files to be relative, not absolute. All of the pivot tables use the same data connection, so I figured it shouldn't be too challenging to write a macro that would update the data connection to refer to the correct text file and have a button linked to the macro that would update the file paths and refresh the data for me.

I'm not overly familiar with VBA and the online documentation seem to be pretty bad, so I haven't been able to get this working -- I can create the correct file path and can refresh the data, but I haven't been able to figure out how to update the connection to use the new file path but retain all its old import/file parsing settings. I have also tried recording a macro while manually updating the data source, but for some reason that always gives me errors which interrupt the recording, so that hasn't helped.

The following is the connection string and command text currently used by the connection, but there's nothing about how to parse/import the data (the file being tab-delimited or having headers in the first column, etc), so I'm not sure how to make sure the connection keeps that data.

Connection String:

DefaultDir=C:/directoryPath;Driver={Microsoft Text Driver (*.txt; *.csv)};
  DriverId=27;FIL=text;MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;
  SafeTransactions=0;Threads=3;UserCommitSync=Yes;

Command Text:

SELECT *
FROM tableName.txt tableName

If anyone knows how to write a macro that will update the path in the connection to the text file please share the code, or if you know how to just make the path relative that'd be great too. Any help would be greatly appreciated!

EDIT:

I've been messing around with it a bit more and I was able to change the connection strings to use the new path. However, when I go to refresh the pivot table it imports all the data as text instead of guessing whether it should be numeric, etc, (although it does get the column headers from the first line of the text file, at least). Any ideas on how to tell it to guess the data types (or just keep the old data types)? The code I'm using right now is:

Public Sub Test()
    Dim wb As Excel.Workbook
    Dim pc As PivotCache
    Dim path As String

    Set wb = ActiveWorkbook
    path = wb.path

    For Each pc In wb.PivotCaches
        'Debug.Print pc.Connection
        pc.Connection = "ODBC;DBQ=" & path & ";DefaultDir=" & path & ";Driver={Microsoft Text Driver (*.txt; *.csv)};DriverId=27;FIL=text;MaxBufferSize=2048;MaxScanRows=8;PageTimeout=5;SafeTransactions=0;Threads=3;UserCommitSync=Yes"

    Next
End Sub

回答1:

Ok, so I got it working and thought I'd share. I cycled through each connection in the workbook and changed its path to the new path to the textfiles (created by getting the path of the active workbook and appending the name of the directory of the textfiles). Also, in order to make sure it imported the text file correctly every time I needed to include a 'schema.ini' file with the import information (in the same directory as the text file).



回答2:

I'm not completely familiar with creating pivot tables in that way exactly, but usually you can get to the information of the pivot table like Connection by looking at the QueryTable object. Check out this example:

Option Explicit

Public Sub UpdatePivotTableConnections()
    Dim ws As Excel.Worksheet
    Dim qt As Excel.QueryTable
    Dim fileName As String

    For Each ws In ThisWorkbook.Worksheets
        For Each qt In ws.QueryTables
            fileName = GetFileName(qt)
            MsgBox "The file name for PivotTable '" & qt.Name & "' is: " & fileName
        Next
    Next
End Sub

Public Function GetFileName(ByRef qt As QueryTable) As String
    Dim s() As String
    s = Split(qt.Connection, "\")
    GetFileName = s(UBound(s))
End Function

It's not a complete answer, but it's a start (I don't like posting incomplete answers, but it was the only way to show you a code example.) See what you get with that info, if you can access the information from there, try looking at the QueryTable.Connection string and see how you can parse it and replace it for each PivotTable.



回答3:

I have found this, and there are many properties followed for the same..

    With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;\\Path\To\CSV\Folder\CSV_Data.csv" _
    , Destination:=Range("$A$1"))
    .CommandType = 0
    .Name = "Book1"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 437
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = True
    .TextFileSemicolonDelimiter = True
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
    End With
    End Sub