vba访问将多个表附加到一个表中

时间:2015-06-11 17:25:33

标签: vba ms-access append

首先,我是编程新手。

问题我已经从互联网上的许多例子中构建了下面的代码。 该数据库名为" Code Holder"这时我有一张桌子"测试"并且在该表中我想要追加与数据库中一样多的表。

  1. 所有表格的所有列都相同
  2. "测试"以外的表名。将改变
  3. 到目前为止我的内容如下: 代码运行正常,但我似乎无法将每个表附加到"测试"表,每个表在SQL字符串中显示为空白

    Sub append4()
        Dim db As Database
        Dim tdf As TableDef
        Dim rs As Recordset         
        Set db = currentdb()
        Set rs = db.OpenRecordset("test")
    
        For Each tdf In db.TableDefs
                    StrSQL = "INSERT INTO " & "test" & " " & _
                    "SELECT * " & _
                    "FROM " & "rs!tablename" & " ;"
                DoCmd.RunSQL StrSQL
            Next tdf
    
        Set db = Nothing
    
    End Sub
    

    我想说我没有设置rs。没错,但我不确定。 任何帮助将不胜感激。

    由于

1 个答案:

答案 0 :(得分:0)

下午,在发布后,我发现了真正有用的东西。下面是更新的VBA代码,经过测试,它适用于我。

谢谢Barett,是的,我错误地引用了一张桌子,但是当你长时间盯着某个东西时会发生什么。

如果您愿意,可随意复制和使用

'please note there are a few things that one assumes while using this code
'1 all tables column headers are the same
'2 this was used with Access 2010


Sub testeroony2()


Dim db As DAO.Database
Dim tdf As DAO.TableDef
'you can set this database to other databases if you wanted too
Set db = currentdb
For Each tdf In db.TableDefs
    ' ignore system and temporary tables
    'if you want to use it for your own use then you will need to change "test" that is the main table that gets uploaded too
    If Not (tdf.Name Like "MSys*" Or tdf.Name Like "~*" Or tdf.Name Like "test") Then
                'you will need to also change "test" below to the main table you want appended too
                StrSQL = "INSERT INTO " & "test" & " " & _
                "SELECT * " & _
                "FROM " & tdf.Name & " ;"
            DoCmd.RunSQL StrSQL
    End If
Next
Set tdf = Nothing
Set db = Nothing
End Sub