是否可以从Excel宏向AccessDB写入数据?

时间:2009-08-31 12:06:17

标签: excel ms-access

是否可以从Excel宏向AccessDB写入数据,怎么做?

我有一个小的MBD文件,我想从excel表中导入数据?

2 个答案:

答案 0 :(得分:1)

Sub DAOFromExcelToAccess()
' exports data from the active worksheet to a table in an Access database
' this procedure must be edited before use
Dim db As Database, rs As Recordset, r As Long
    Set db = OpenDatabase("C:\FolderName\DataBaseName.mdb") 
    ' open the database
    Set rs = db.OpenRecordset("TableName", dbOpenTable) 
    ' get all records in a table
    r = 3 ' the start row in the worksheet
    Do While Len(Range("A" & r).Formula) > 0 
    ' repeat until first empty cell in column A
        With rs
            .AddNew ' create a new record
            ' add values to each field in the record
            .Fields("FieldName1") = Range("A" & r).Value
            .Fields("FieldName2") = Range("B" & r).Value
            .Fields("FieldNameN") = Range("C" & r).Value
            ' add more fields if necessary...
            .Update ' stores the new record
        End With
        r = r + 1 ' next row
    Loop
    rs.Close
    Set rs = Nothing
    db.Close
    Set db = Nothing
End Sub

答案 1 :(得分:0)

您是否考虑过相反的方法?在Access中附加Excel工作表然后使用make表查询将数据添加到新表或现有表很容易,这样可以避免编码。