我有以下 Excel VBA 代码,它读取 Excel 中的列并将值导入 Access 中的表:
Dim Cn As Object
Dim strSql As String
Dim strConnection As String
Set Cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\myDatabase.accdb"
Cn.Open strConnection
For i = 2 To ActiveSheet.UsedRange.Rows.Count
Cn.Execute "INSERT INTO myTable VALUES (" & Cells(i, 1).Value & ")"
Next i
Cn.Close
Set Cn = Nothing
问题是,即使列中的值在技术上是数字(0001234、0123456、0001 等),列的格式为文本,而 Access 表中的字段格式为文本。但是上面的代码仍然将它们作为数字导入,这会删除前导 0(s)。有没有办法强制它们作为文本值导入?
谢谢!!
编辑:我尝试在列中的值前面加上一个单引号(例如:'0001234 而不是 0001234),但它们仍然作为数字导入。
EDIT2:我也试过这个:
Dim Cn As Object
Dim strSql As String
Dim strConnection As String
Dim CellValue as String
Set Cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\myDatabase.accdb"
Cn.Open strConnection
For i = 2 To ActiveSheet.UsedRange.Rows.Count
CellValue = Cells(i, 1).Value
Cn.Execute "INSERT INTO myTable VALUES (" & CellValue & ")"
Next i
Cn.Close
Set Cn = Nothing
但是这些值仍然会在导入时删除前导 0。
EDIT3 - 解决了!!我不得不在Cells(i, 1).Value
. 现在领先的 0 保持不变!
Dim Cn As Object
Dim strSql As String
Dim strConnection As String
Set Cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\CarrierAudit.accdb"
Cn.Open strConnection
For i = 2 To ActiveSheet.UsedRange.Rows.Count
Cn.Execute "INSERT INTO Pinnacol_NDC VALUES (""" & Cells(i, 1).Value & """)"
Next i
Cn.Close
Set Cn = Nothing