使用Excel VBA从Excel导出到Access 2007

时间:2015-07-24 16:11:28

标签: vba ms-access-2007 excel-2007

我需要导出工作表的内容以附加到访问数据库表(2007年),我试图从Excel电子表格中的模块运行它。该表有一个主键,它是一个自动编号,我尝试运行下面的模块,在电子表格中有和没有空的第一列,以匹配电子表格列和表格列。此外,表格中的最后一个字段是一个复选框Y \ N,我在电子表格的TRUE和FALSE值中输入了最后一列。但是当我运行模块时,我得到了“已完成”的msgbox,但表格没有更新。电子表格和数据库都位于C:的位置。我做错了什么?

Private Sub AddData()


Dim strMyPath As String, strDBName As String, strDB As String, strSQL   
 As  String
Dim i As Long, n As Long, lastRow As Long, lFieldCount As Long
Dim adoRecSet As New ADODB.Recordset
Dim connDB As New ADODB.Connection

strDBName = "CMDB.mdb"
strMyPath = ThisWorkbook.Path
strDB = strMyPath & "\" & strDBName

"Microsoft.ACE.OLEDB.12.0". The ACE Provider can be used for both the    
  Access .mdb & .accdb files.
  connDB.Open ConnectionString:="Provider = Microsoft.ACE.OLEDB.12.0;    
  data source=" & strDB


Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(18)

Set adoRecSet = New ADODB.Recordset

strTable = "Asset_Table"
adoRecSet.Open Source:=strTable, ActiveConnection:=connDB,    
CursorType:=adOpenStatic, LockType:=adLockOptimistic


lFieldCount = adoRecSet.Fields.Count
'determine last data row in the worksheet:
lastRow = ws.Cells(Rows.Count, "A").End(xlUp).Row


For i = 2 To lastRow

   adoRecSet.AddNew

   For n = 0 To lFieldCount - 1
    adoRecSet.Fields(n).Value = ws.Cells(i, n + 1)
   Next n

   adoRecSet.Update

Next i



adoRecSet.Close
connDB.Close
Set adoRecSet = Nothing
Set connDB = Nothing

MsgBox "Finished"

End Sub
编辑:下面的Evans和ChipsLetten的建议得到了帮助,我已经解决了这个问题。我更改了行数计算并添加了一个If来处理自动编号,因为芯片建议如下。

Dim b As Long  
b = ws.UsedRange.Rows.Count

For i = 2 To b - 1
 adoRecSet.AddNew
  For n = 0 To lFieldCount - 1
    If Not adoRecSet.Fields(n).Properties("ISAUTOINCREMENT") Then    
     adoRecSet.Fields(n).Value = ws.Cells(i, n + 1).Value
   End If

 Next n
adoRecSet.Update

Next i

1 个答案:

答案 0 :(得分:1)

您可以在尝试向其中写入值之前测试该字段以查看它是否为自动增量字段。尝试下面的代码,对我来说没问题(Excel 2007但Access 2010)

For i = 2 To lastRow

    adoRecSet.AddNew

    For n = 0 To lFieldCount - 1
        If Not adoRecSet.Fields(n).Properties("ISAUTOINCREMENT") Then
            adoRecSet.Fields(n).Value = ws.Cells(i, n + 1).Value
        End If
    Next n

    adoRecSet.Update

Next i

对Excel表格的最后一列使用TRUE / FALSE可以正常使用。