我不知道这是否会帮助你。这是我用于质量控制程序的例程。csv 文件有 4 行,最多 20 行,因此 arrData(80) 但它也可以少于 20 行。我用它从 AutoCAD 绘图(从不超过 20)中取出尺寸并填写文本框。
Kim 是对的,每次都必须是相同形式的 csv 格式。
Private Sub Import_Click()
On Error GoTo HandleError
RoutineName = Form.Name & " Import_Click Event"
Dim Detline As String 'Record form selected file
Dim I As Integer 'Index for rows (table & array)
Dim FF As Integer 'next file number available for use by the Open statement
Dim dlgOpen As FileDialog
Set dlgOpen = Application.FileDialog(msoFileDialogOpen)
With dlgOpen
With .Filters
.Clear
.Add "Import csv or txt", "*.csv; *.txt", 1
.Add "All Files", "*.*", 2
End With
.InitialFileName = "c:\QControl\"
.FilterIndex = 1
.AllowMultiSelect = False
.Title = "Select document to import"
.ButtonName = "Ok"
.Show
If .SelectedItems.Count > 0 Then
SelectedFile = .SelectedItems(1)
End If
End With
ReDim arrData(80)
DoCmd.GoToRecord acDataForm, "Main QC Form", acNewRec
I = 1 ' initalize counter
FF = FreeFile 'Use FreeFile to supply a file number that is not already in use.
Open SelectedFile For Input As #FF
Do While Not EOF(FF) 'Read selected file line by line
Line Input #FF, Detline
arrData = Split(Detline, ",")
Me.Controls("letter" & I) = arrData(0)
Me.Controls("printdim" & I) = arrData(1)
Me.Controls("stepnumber" & I) = arrData(2)
Me.Controls("Gage" & I) = arrData(3)
I = I + 1 'increment counter
Loop
RunCommand acCmdSaveRecord ' Save the Record you're looking at
Me.Requery ' Force the Recordset of the Form to update
Me.Form1.Requery
Close #FF 'close text file
DoCmd.GoToRecord , , acLast
Exit_Import_Click:
DoCmd.SetWarnings True
Exit Sub
HandleError:
RtnCode = ErrorHandler (EH_NumError:=Err.Number,DescError:=
Err.Description,NameRoutine:=RoutineName)
Resume Exit_Import_Click
End Sub