简体   繁体   English

将CSV文件中的数据从特定位置导入excel

[英]Import data from a CSV file into excel from a specific location

I am trying to put together a VBA code to import data from a CSV file stored in a specific location and paste the data in my desired worksheet. 我试图将VBA代码放在一起,以便从存储在特定位置的CSV文件导入数据,并将数据粘贴到所需的工作表中。 What I have done is I simply recorded a macro where I have stored the file location in a string variable named 'path' and used this variable to specify the file location. 我所做的只是简单地记录了一个宏,在其中将文件位置存储在名为“ path”的字符串变量中,并使用此变量指定了文件位置。 But after executing the code, its showing an error saying that "Excel can not find the text file to refresh this external data range". 但是执行代码后,它显示一个错误,指出“ Excel找不到文本文件来刷新此外部数据范围”。 Below is provided the code: Advanced thanks for your help. 下面提供了代码:高级感谢您的帮助。

Sub Macro1()
    Dim path As String
    path = InputBox("Provide the location of the file")

    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;path.csv" _
        , Destination:=Range("$A$1"))
        .Name = "AO2576.log.0240021"
        .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 = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
        1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

You should open the file with a file dialog and set accordingly the QueryTable. 您应该使用文件对话框打开文件,并相应地设置QueryTable。

Dim path: path = Application.GetOpenFilename("CSV Files (*.csv), *.csv")
If path = False Then Exit Sub 
With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & path, Destination:=Range("A1"))
    ...
End With

Notice that "TEXT;path.csv" is a hardcoded string, it is not set from the file's name just selected by user. 请注意, "TEXT;path.csv"是一个硬编码的字符串,它不是从用户刚刚选择的文件名中设置的。 "TEXT;" & path "TEXT;" & path is the way to go. "TEXT;" & path是要走的路。

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

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