是VB编程的新手,我有一个要求,其中将有一个已经在Access中创建的表,我需要编写将读取文件并在记录中输入数据的代码。请帮我解决这个问题。我使用Access作为我的数据库
输入文件是.CSV文件,格式为:
FIRST_NAME, LAST_NAME, HOME_ADD, COMPANY, DESIG
Mark , Taylor , UK , XYZ , ABC
Mark , Taylor , UK , XYZ , ABC
Mark , Taylor , UK , XYZ , ABC
Mark , Taylor , UK , XYZ , ABC
Mark , Taylor , UK , XYZ , ABC
Mark , Taylor , UK , XYZ , ABC
Mark , Taylor , UK , XYZ , ABC
这个值sholud可以从“C:\ input \ data.csv”文件夹中读取并写入已创建的Access表中。
先谢谢
答案 0 :(得分:0)
我不确定你是否会提前知道这些字段。我会假设您在文件打开之前不知道。另外,我假设你正在使用ADO。
Private Sub InsertCsvDataIntoTable(ByRef in_sCsvFileName As String, _
ByRef in_oConn As ADODB.Connection, _
ByRef in_sTableName As String)
Dim iFileNo As Integer
Dim sLine As String
Dim vasFields As Variant
Dim lIndex As Long
Dim sSQL_InsertPrefix As String
Dim sSQL As String
iFileNo = FreeFile
Open in_sCsvFileName For Input As #iFileNo
If EOF(iFileNo) Then
Exit Sub
End If
' Read field names from the top line.
Line Input #iFileNo, sLine
' Note that in a "proper" CSV file, there should not be any trailing spaces, and all strings should be surrounded by double quotes.
' However, the top row provided can simply be used "as is" in the SQL string.
sSQL_InsertPrefix = "INSERT INTO " & in_sTableName & "(" & sLine & ") VALUES("
Do Until EOF(iFileNo)
Line Input #iFileNo, sLine
' Initialise SQL string.
sSQL = sSQL_InsertPrefix
' Again, in a proper CSV file, the spaces around the commas shouldn't be there, and the fields should be double quoted.
' Since the data is supposed to look like this, then the assumption is that the delimiter is space-comma-space.
vasFields = Split(sLine, " , ")
' Build up each value, separated by comma.
' It is assumed that all values here are string, so they will be double quoted.
' However, if there are non-string values, you will have to ensure they don't get quoted.
For lIndex = 0 To UBound(vasFields) - 1
sSQL = sSQL & "'"
sSQL = sSQL & vasFields(lIndex)
sSQL = sSQL & "'"
sSQL = sSQL & ","
Next lIndex
' This chunk of code is for the last item, which does not have a following comma.
sSQL = sSQL & "'"
sSQL = sSQL & vasFields(lIndex)
sSQL = sSQL & "'"
sSQL = sSQL & ")"
' Run the SQL command.
in_oConn.Execute sSQL
Loop
Close #iFileNo
End Sub
答案 1 :(得分:0)
Access已支持从CSV文件导入记录,因此可以通过启动和控制Access实例轻松完成此操作。
With CreateObject("Access.Application")
.OpenCurrentDatabase "C:\Database1.accdb"
.DoCmd.TransferText , , "Table1", "c:\input\data.csv", True
.Quit
End With
True
TransferText
参数指定您的CSV文件包含标题行。