我在网上发现了一些将我的Excel数据导出到Access表的代码。问题是它正确地创建了标题但根本没有填充数据。如何告诉Excel浏览数据并导出这些字段?
以下是代码:
Sub Z_CreateTable()
'If this subroutine throws errors, remember to go to:
'Tools > References and select 'Microsoft ActiveX Data Objects #.# Library'
Dim dbConnectStr As String
Dim Catalog As Object
Dim cnt As ADODB.Connection
Dim dbPath As String
Dim strSQL As String
Dim rngDB As Range
Dim wbPath As String
Dim stSQL As String
Dim strTable As Object
'Set database name here
dbPath = "T:\Projects\testdata1.mdb"
dbConnectStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & dbPath & ";"
'Create new database
Set Catalog = CreateObject("ADOX.Catalog")
Catalog.Create dbConnectStr
'Connect to database and insert a new table
Set cnt = New ADODB.Connection
cnt.CursorLocation = adUseServer
With cnt
.Open dbConnectStr
.Execute "CREATE TABLE tblSample ([FIELD1] text(50) WITH Compression, " & _
"[NAME] text(150) WITH Compression, " & _
"[BLANK] text(10) WITH Compression, " & _
"[CLASSID] text(10) WITH Compression, " & _
"[TYPE] text(5) WITH Compression, " & _
"[FIELD2] text(5) WITH Compression, " & _
"[FIELD3] text(5) WITH Compression, " & _
"[FIELD4] text(15) WITH Compression, " & _
"[START YEAR] text(15) WITH Compression, " & _
"[END YEAR] text(10) WITH Compression)"
End With
Set cnt = Nothing
End Sub
答案 0 :(得分:2)
请参阅:asp and ms-access db - how to import data from xls file您可以使用相当标准的SQL从Excel更新,而无需先创建表,也不需要遍历行,这非常慢。
答案 1 :(得分:0)
您是否尝试从Access数据库导入?您可以先创建自己的表,这样可以更好地控制字段数据类型和索引。
答案 2 :(得分:0)
这段代码确实只会创建表格。要插入记录,您需要使用“INSERT INTO tblSample”然后每个Excel行执行一次。
我不知道如何在VBA中执行此操作,但我可以使用For Each row In {table}.Rows...Next
语句在VB中执行此操作,因此VBA中的Googling For Each
语法可能会对您有所帮助。或者也许有人在这里可以给你一个很好的例子。
编辑: 接近这一点可能会有效
For i = startRow to endRow
cnt.Execute "INSERT INTO tblSample VALUES (" & _
Cells(i, 1).Value & "," & Cells(i, 2).Value & _
--And so on
& ")"
Next i
您必须设置开始和结束行的值。此循环将遍历您范围中的每一行,并将该行中单元格的值插入到您指定的字段中。您需要使订单与表格中的列相同,因此您可能首先使用Cells(i, 2).Value
。
尝试在With
之后,Set cnt = Nothing
之前立即执行。
编辑:使用SELECT INTO
.Execute "SELECT * INTO tblSample FROM "[{Your version of Excel};
DATABASE={Your Excel spreadsheet}].[{Your sheet name}]"
替换现有的.Execute块。