一,以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