Excel 2016 VBA,Windows 10
我试图使用VBA获取数据。我想使用相对参考。我只是想从Raw Keyword.csv'中获取数据。在与xlsm文件相同的文件夹中。它似乎永远不会认识到相对路径。我尝试使用它周围的所有引号构建它(选项A,首选)并将该变量传递给Folder.Files。我看到了一个建议,将Path和文件名放在File.Contents中的另一个线程(下面的链接)中,但这也没有用。有什么建议吗?
' Option A
Dim RawK As String
RawK = """""" & ActiveWorkbook.Path & "\Raw Keyword.csv" & """"""
ActiveWorkbook.Queries.Add Name:="Query Keyword", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(RawK)...
' Option B:
ActiveWorkbook.Queries.Add Name:="Query Keyword", Formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Csv.Document(File.Contents(ActiveWorkbook.Path & ""\Raw Keyword.csv"") ...
在这里看到类似的答案,但没有运气。 Relative path for Folder.Files
答案 0 :(得分:0)
我认为这是你正在寻找的东西:
Sub tgr()
Dim CSVName As String
Dim qt As Object
CSVName = "Raw Keyword"
On Error Resume Next
Set qt = ActiveWorkbook.Connections(CSVName)
On Error GoTo 0
If qt Is Nothing Then
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & ActiveWorkbook.Path & "\" & CSVName & ".csv", Destination:=Range("$A$1"))
.FieldNames = True
.RefreshOnFileOpen = True
.RefreshStyle = xlInsertDeleteCells
.AdjustColumnWidth = True
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileCommaDelimiter = True
.Refresh BackgroundQuery:=False
End With
Else
qt.Refresh
End If
End Sub