1. 程式人生 > 其它 >把CSV檔案或以逗號分割的TXT檔案匯入Excel

把CSV檔案或以逗號分割的TXT檔案匯入Excel

一,以OLEDB連線方式匯入,程式碼如下:

Sub 匯入txt資料到工作表()
   Dim con As New ADODB.Connection
   Dim res As New ADODB.Recordset
   Dim str As String
   str = ThisWorkbook.Path & "\"
   With con
      .Provider = "Microsoft.ACE.OLEDB.12.0;Extended Properties=Text"
      .Open str
   End With
   Dim sql As String
   sql = "select * from [資料.txt] order by 編號"
   res.Open sql, con, adOpenKeyset, adLockOptimistic
   Range("A1").CurrentRegion.Clear
   Dim i As Integer
   For i = 0 To res.Fields.Count - 1
      Cells(1, i + 1) = res.Fields(i).Name
   Next i
   Range("A2").CopyFromRecordset res
   res.Close
   con.Close
   Set res = Nothing
   Set con = Nothing
End Sub

  

二,以ODBC連線方式,程式碼如下

Sub 匯入txt資料到工作表()
   Dim con As New ADODB.Connection
   Dim res As New ADODB.Recordset
   Dim str As String
   str = ThisWorkbook.Path & "\"
   With con
      .Provider = "MSDASQL;"
      .ConnectionString = "Driver={microsoft text driver (*.txt; *.csv)};DBQ=" & str
      .Open
   End With
   Dim sql As String
   sql = "select * from [資料.txt] order by 編號"
   res.Open sql, con, adOpenKeyset, adLockOptimistic
   Range("A1").CurrentRegion.Clear
   Dim i As Integer
   For i = 0 To res.Fields.Count - 1
      Cells(1, i + 1) = res.Fields(i).Name
   Next i
   Range("A2").CopyFromRecordset res
   res.Close
   con.Close
   Set res = Nothing
   Set con = Nothing
End Sub