VBA,导入CSV分割为";"表

时间:2017-12-06 09:38:35

标签: excel vba excel-vba csv

我正在尝试导入以分号分隔的CSV文件";"进入一个excel对象,以便我以后可以使用它。

理想情况下,我想使用ADO,DAO或ADODB,因此我也可以对该对象运行SQL查询,并获取特定字段的总和或字段总数等。

到目前为止,我已经获得了下面的代码,但它没有将数据拆分为";",所以它全部返回为1个字段而不是可以处理的多个字段。

Sub Import()
   Dim conn As New ADODB.Connection
   Dim rs As New ADODB.Recordset
   Dim f As ADODB.Field

   Dim csvName, csvPath

    csvPath = ActiveWorkbook.path
    csvName = "fileName.csv"

   conn.Open "DRIVER={Microsoft Text Driver (*.txt; *.csv)};DBQ=" & csvPath & ";"
   rs.Open "SELECT * FROM " & csvName, conn, adOpenStatic, adLockReadOnly, adCmdText

   Debug.Print rs.Fields

   While Not rs.EOF
      For Each f In rs.Fields
         Debug.Print f.Name & "=" & f.Value
      Next
   Wend
End Sub

任何人都可以告诉我如何通过&#34 ;;"来分割数据。并使用SQL查询查询它?或者是我可以将CSV加载到某些列并查询某些列的其他对象。

2 个答案:

答案 0 :(得分:2)

以下是示例:

Public Sub QueryTextFile()

    Dim rsData As ADODB.Recordset
    Dim sConnect As String
    Dim sSQL As String

    ' Create the connection string.
    sConnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
               "Data Source=C:\Files\;" & _
               "Extended Properties=Text;"

    ' Create the SQL statement.
    sSQL = "SELECT * FROM Sales.csv;"
    Set rsData = New ADODB.Recordset
    rsData.Open sSQL, sConnect, adOpenForwardOnly, _
                adLockReadOnly, adCmdText

    ' Check to make sure we received data.
    If Not rsData.EOF Then
        ' Dump the returned data onto Sheet1.
        Sheet1.Range("A1").CopyFromRecordset rsData
    Else
        MsgBox "No records returned.", vbCritical
    End If

    ' Clean up our Recordset object.
    rsData.Close
    Set rsData = Nothing

End Sub

答案 1 :(得分:0)

我发现唯一可用的答案是在当前文件夹中创建一个ini文件,并在ini文件中输入分隔符。

iniPath = activeworkbook.path & "\"
iniName = "schema.ini"
iniPathName = iniPath & iniName
If Not fso.FileExists(iniPathName) Then
    fso.CreateTextFile (iniPathName)
End if