问题
I'm hoping this can be done as what I've been finding so far is that Excel does not support relative paths for workbook connections. What we have here is an Excel workbook that auto-updates the worksheets from CSV files. These pull in the data from a hard coded folder (c:\temp\premiumreports\name_of_CSV_file.csv). This method forces me to put everything into c:\temp\premiumreports everytime or if I send the file to a customer they have to create the same directory structure. What I would like to do is place my xlsx file into any folder (c:\report or the user's desktop) with the necessary CSV files and when I open the xlsx the data is imported automatically. Is this possible?
Current Workbook Connection
Thanks!
回答1:
If the work book file is always located in the same folder as the CSV file you can utilize the ActiveWorkbook.Path method to set a relative path.
Example assuming csv file name and connection name are the same:
Sub refreshMsgConnection()
Dim csvFileName As String
csvFileName = "msg_by_weeks.csv"
Dim filePath As String
filePath = ActiveWorkbook.path
Dim conString As String
conString = "TEXT;" & filePath & "\" & csvFileName
With ActiveWorkbook.Connections("msg_by_weeks").Ranges.Item(1).QueryTable
.connection = conString
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.TextFilePromptOnRefresh = False
.Refresh BackgroundQuery:=False
End With
End Sub
You may have to play with some of the settings based on your configuration such as delimiters etc. If you're having trouble, record a macro while you setup a new connection with the desired format and then copy the settings in this sub.
If the file is not found, it will pop up a file selection box for the user to locate the desired file.
回答2:
I found the answer!
You may find the current file path putting in any cell of your workbook the formula
=LEFT(CELL("filename",$A$1),FIND("[",CELL("filename",$A$1),1)-1)
name this cell somehow, let say "FilePath" and generate absolute path in query like
let
FilePath = Excel.CurrentWorkbook(){[Name="FilePath"]}[Content]{0}[Column1],
FullPathToFile1 = FilePath & "Name1.xlsx"
Source = Excel.Workbook(File.Contents(FullPathToFile1), null, true)
in
source: https://techcommunity.microsoft.com/t5/Excel/Power-Query-Source-from-Relative-Paths/m-p/206267/highlight/true#M6836
来源:https://stackoverflow.com/questions/40534107/relative-paths-within-excel-for-csv-imports