简体   繁体   English

使用Excel宏更改数据透视表外部数据源路径

[英]Changing pivot table external data source path with Excel macro

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. 我正在处理MS Excel中的一个项目,该项目中有多个数据透视表,这些数据透视表使用Microsoft文本驱动程序从带有制表符分隔的文本文件中读取数据,该文件的第一行(与Excel文件位于同一目录)的列名。 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. 我遇到了一个问题,当我将文本和Excel文件复制到新目录并尝试刷新数据时会显示找不到文本文件。 Unfortunately there seems to be no way to tell Excel I want the paths to the text files to be relative, not absolute. 不幸的是,似乎没有办法告诉Excel我希望文本文件的路径是相对的,而不是绝对的。 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. 我对VBA不太熟悉,在线文档似乎还很糟糕,因此我无法使它正常工作-我可以创建正确的文件路径并可以刷新数据,但是我一直没有能够弄清楚如何更新连接以使用新文件路径,但保留所有旧的导入/文件解析设置。 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

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). 另外,为了确保每次我需要在导入信息中包含一个“ schema.ini”文件(与文本文件位于同一目录中)时,都正确导入了文本文件。

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. 我并不完全熟悉以这种方式创建数据透视表,但是通常您可以通过查看QueryTable对象来获取诸如Connection之类的数据透视表的信息。 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. 这不是一个完整的答案,但这是一个开端(我不喜欢发布不完整的答案,但这是向您展示代码示例的唯一方法。)如果可以从中获取信息,请参阅此信息,请尝试查看QueryTable.Connection字符串,看看如何解析它并将其替换为每个数据透视表。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM