将csv文件导入工作簿

时间:2015-05-13 14:33:54

标签: excel vbscript import-from-excel

我希望能够单击按钮并选择要导入的文件。我已经完成了这个但是在之后它说我的文件已被导入没有任何反应。

我缺少什么?

Sub GetImportFileName()
    Dim Filt As String
    Dim Title As String
    Dim FileName As Variant
    Dim FilterIndex As Integer

    Filt = "Comma Separated Files (*.csv),*.csv,"
    FilterIndex = 5
    Title = "Select a File to Import"

    FileName = Application.GetOpenFilename _
    (FileFilter:=Filt, _
     Title:=Title)

     If FileName = False Then
        MsgBox "No file was selected."
        Exit Sub
     End If

     MsgBox "You selected " & FileName      
End Sub

1 个答案:

答案 0 :(得分:1)

我没有看到任何导入CSV的代码。您只获取FileName。你遗漏了这样的东西(Comma (,)作为分隔符)

With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;" & fileName & "", Destination:=Range("$A$1" _
    ))
    .CommandType = 0
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 852
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With