How to Import CSV data into Excel after selecting

2019-09-18 10:03发布

I need to be able to import column data from a Comma Delimited Excel Sheet into a new sheet using the get external data function. I wish to originally select the file in a userform but cannot figure out how to mate the file selected in the userform with the Import Command. Code for the import module is attached.

  With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;C:\Users\---\Rainflow Data\J-Rain Outputs\Moment(N-mm).csv" _
    , Destination:=Range("$A$1"))
    .CommandType = 0
    .Name = "Moment(N-mm)"
    .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 = True
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

Instead of referencing the file path that I selected when recording this macro I need it to open the file I select in the userform. Any help would be greatly appreciated.

Thanks

标签: excel vba csv
1条回答
Emotional °昔
2楼-- · 2019-09-18 10:24

Assuming the variable yourFilePath has the path to the selected file you can do this:

With ActiveSheet.QueryTables.Add(Connection:= "TEXT;" & yourFilePath, _
                                 Destination:=Range("$A$1"))
    .CommandType = 0
    .Name = "Moment(N-mm)"
    .FieldNames = True
    .RowNumbers = False
    'etc
查看更多
登录 后发表回答