你可以嘗試下面的代碼。將其粘貼到模塊中並進行必要的更改以適應您的需求。用你需要的字段和他們的類型來設計一個表格,並在下面引用它。使用將運行事件過程的命令按鈕創建窗體。調用你創建的模塊。
Public Sub ImportTextFile()
' to use the ADODB.Recordset, be sure you have a reference set to ADO
Dim rst As ADODB.Recordset
Dim strFile As String
Dim strInput As String
Dim varSplit As Variant
Dim intCount As Integer
Set rst = New ADODB.Recordset
' CHANGE THE TABLE NAME HERE
rst.Open "TblNameHere", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
' CHANGE THE TEXT FILE NAME AND LOCATION HERE
strFile = "C:\Desktop\fullextract.txt"
Open strFile For Input As #1
Dim i As Integer
Do Until EOF(1)
' This counter is just to get to the applicable line before importing
intCount = intCount + 1
' reads the text file line by line
Line Input #1, strInput
' starts importing on the second line. Change the number to match which line you
' want to start importing from
If intCount >= 2 Then
' creates a single dimension array using the split function
varSplit = Split(strInput, ",", , vbTextCompare)
' adds the record
With rst
.AddNew
' change the range 0 To 254 to fit your needs. I was importing 254 fields.
For i = 0 To 254
.Fields(i) = varSplit(i)
Next i
.Update
End With
End If
Loop
' garbage collection
Close #1
rst.Close
Set rst = Nothing
End Sub
在Access中,如果將字段的數據類型設置爲***文本***,那麼您被限制爲255個字符。如果您需要存儲超過255個字符,則必須將數據類型設置爲***備忘錄***。實際上,導入CSV文件會給您帶來問題。相反,您最好導入製表符分隔的文本文件。 VBA是完成工作的最好和最簡單的方法。 – Linger
假設表已經創建了正確的數據類型,數據的導入仍會截斷爲備註字段的255個字符。 – Sun