0

Excel 2016 VBA,Windows 10

我正在尝试使用 VBA 获取数据。我想使用相对参考。我只想从与 xlsm 文件相同的文件夹中的“Raw Keyword.csv”获取数据。它似乎永远不会识别相对路径。我尝试用它周围的所有引号构建它(选项 A,首选)并将该变量传递给 Folder.Files。我看到一个建议将 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"") ...

在这里看到了类似的答案,但没有运气。 Folder.Files 的相对路径

4

1 回答 1

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
于 2018-03-15T13:59:48.093 回答