Vba将CSV文件导入Excel

时间:2016-06-13 08:24:27

标签: vba excel-vba csv excel

我尝试使用VBA代码将Csv文件导入Excel,我希望它能够与所有Csv文件一起使用,但它没有。这是我的代码:

Function ImportCSV(ByVal Filename As String, _
                   ByVal Worksheet As String, _
                   ByVal StartCell As String) As Boolean
 On Error GoTo Catch

    Dim strConnectionName As String
    strConnectionName = "TEXT;" + Filename

    With Worksheets(Worksheet).QueryTables.Add(Connection:=strConnectionName, _
                                               Destination:=Worksheets(Worksheet).Range(StartCell))
        .Name = Filename
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlOverwriteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True 'False
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = True 'False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .Refresh BackgroundQuery:=False
    End With

        ImportCSV = True
        Exit Function

Catch:
        ImportCSV = False

End Function

这是功能代码

2990 kr

我怎么能纠正它?有人可以帮助我PLZ!

2 个答案:

答案 0 :(得分:0)

您可以简化并使用以下内容打开文件:

SwingWorker.done()

有关此方法的更多详细信息here (MSDN link)

答案 1 :(得分:0)

这里有一个很好的解释:

https://sitestory.dk/excel_vba/csv-file-import.htm

使用我在案例中应用的代码:

 Sub OpenCSV()

 Dim sPath As String
 sPath = ThisWorkbook.Path & "\Site_survey_form2.csv"
 Workbooks.OpenText Filename:= _
 sPath, DataType:=xlDelimited, Semicolon:=True, Local:=True
 End Sub

因此,.csv 文件将在单独的工作簿中打开。

如果您想立即将 .csv 内容导入您的工作簿,那么我建议您参考此处的线程:

Is there a way to import data from .csv to active excel sheet?

从那里我准备了以下代码:

 Sub CSV_Import()
 Dim ws As Worksheet, strFile As String, sPath As String

 Set ws = ActiveWorkbook.Sheets("Sheet1") 'set to current worksheet name

 sPath = ThisWorkbook.Path & "\Site_survey_form2.csv"  '"\ your file name

  With ws.QueryTables.Add(Connection:="TEXT;" & sPath, 
  Destination:=ws.Range("A1"))  
 .TextFileParseType = xlDelimited
 .TextFileCommaDelimiter = True
 .Refresh

结尾 结束子