用macros设置Excel数据连接(csv)

我一直在寻找一个解决scheme来解决以下问题,但没有发现任何真正有用的东西:我有一个excel工作表,其中有数据连接到一些csv。 不幸的是,Excel不会将连接保存为绝对path。 理想情况下,我将能够将path设置为相对path,但我会解决一个macros,它允许用户在首次使用前根据这个工作thisworkbook.pathpath更新连接。

该项目在d:\ project \ excel中的excel工作表和d:\ project \ results中的csv文件夹中。 如果我将这个项目作为一个zip文件发送给某个用户,他将解压到c:\ my documents \ project中,他将不得不重新连接10个左右的csv。

我的一般想法是写一个macros(没有真正的代码,因为我是vba的新手,如果我知道代码,我不会问)

 filepath = thisworkbook.path cons = thisworkbook.connections for each cons filename = cons.filename newpath = filepath & filename end for 

我知道这是一个古老的问题,但我现在一直在寻找同样的东西,我终于明白了这一点。 也许有人说过一样的话,但我还没有通过search谷歌search…

可以说你已经有了这些条件:

  1. 您已经在工作簿中设置了数据连接(假设连接pipe理器中的名称是MyData)
  2. 数据连接的目标已经定义,并且是Sheet1中的某个位置
  3. 您有一个单元格(说Sheet2的A1)具有您要连接到的文件名称
  4. 您只需要更改连接正在查找的path,以便遵循工作簿的path

如果是这样,像这样的事情应该做的伎俩。

 Dim fileLoc As String Dim fileName As String fileLoc = ThisWorkbook.Path fileName = Sheet2.Range("A1").Value Dim conString As String conString = "TEXT;" & fileLoc & "\" & fileName Sheet1.QueryTables.Item("MyData").Connection = conString 

随意修改或斟酌,因为你的情况下的需要。

您可以像这样访问连接path

 Sub UpdateConnections() Dim con As WorkbookConnection Dim ConString As String For Each con In ThisWorkbook.Connections ConString = con.Ranges.Item(1).QueryTable.Connection ' Path update code here Next End Sub 

对于文本数据源返回一个string,如"TEXT;C:\My\Path\Documents\FileName.csv"

在testing这个时,我发现改变path也影响了一些其他的属性,所以你可能需要在改变path后重新设置一堆属性。

感谢您的帮助,以下是我最后提出的:

 Sub UpdateAllConnections() For Each cn In ThisWorkbook.Connections cn.Delete Next cn Dim arrConNames(1) As String Dim arrSheetNames(1) As String arrConNames(0) = "test1.csv" arrConNames(1) = "test2.csv" arrSheetNames(0) = "test1" arrSheetNames(1) = "test2" Dim indCon As Integer For indCon = LBound(arrSheetNames) To UBound(arrSheetNames) UpdateConnections arrConNames(indCon), arrSheetNames(indCon) Next End Sub Sub UpdateConnections(ConName As String, SheetName As String) FilePath = ThisWorkbook.Path ResultPath = Replace(FilePath, "Excel-Shell", "Results") ThisWorkbook.Worksheets(SheetName).Select ActiveSheet.Cells.Clear With ActiveSheet.QueryTables.Add(Connection:= _ "TEXT;" & ResultPath & "\" & ConName, Destination:=Range( _ "$A$1")) .Name = ConName .FieldNames = True .RowNumbers = False .FillAdjacentFormulas = False .PreserveFormatting = True .RefreshOnFileOpen = False .RefreshStyle = xlInsertDeleteCells .SavePassword = False .SaveData = True .AdjustColumnWidth = True .RefreshPeriod = 0 .TextFilePromptOnRefresh = False .TextFilePlatform = 850 .TextFileStartRow = 1 .TextFileParseType = xlDelimited .TextFileTextQualifier = xlTextQualifierDoubleQuote .TextFileConsecutiveDelimiter = False .TextFileTabDelimiter = False .TextFileSemicolonDelimiter = True .TextFileCommaDelimiter = False .TextFileSpaceDelimiter = False .TextFileColumnDataTypes = Array(1, 1) .TextFileTrailingMinusNumbers = True .Refresh BackgroundQuery:=False End With End Sub