MS在创建查询时访问堆栈空间

时间:2012-09-25 19:07:24

标签: ms-access access-vba

我正在尝试创建一个Access数据库,它将多个结构相同的数据库链接在一起。这些其他数据库是来自3D模型的导出,它们具有相同的表,但每个数据库中的数据不同。我需要做的是从所有数据库报告,就像它们是一个大数据库。我认为我会这样做是为了创建查询,将每个数据库中的各个相同的表联合到一个查询中,然后我可以在所有其他报告中使用这些查询。我写的一起加入表格的代码如下。我遇到的麻烦是,这段代码在“Set QueryDef ...”行中给出了一个堆栈空间错误。有人能告诉我我做错了吗?

Public Sub CreateUnionQueries()
'On Error GoTo Err_CreateUnionQueries
Dim QueryRs As DAO.Recordset
Dim TableRs As DAO.Recordset
Dim QueryDef As DAO.QueryDef
Dim SQLText As String
Dim qry As QueryDef

'Get list of all Foreign Table Names
Set QueryRs = CurrentDb.OpenRecordset("select distinct ForeignName from msysobjects where ForeignName is not null")

'Loop over list to create union queries
If QueryRs.RecordCount <> 0 Then
    Do While Not QueryRs.EOF
        Set TableRs = CurrentDb.OpenRecordset("select Name from msysobjects where ForeignName = """ & QueryRs![ForeignName] & """")
        Do While Not TableRs.EOF
            SQLText = SQLText & "select * from " & TableRs![Name]
            TableRs.MoveNext
            If Not TableRs.EOF Then
                SQLText = SQLText & " UNION ALL "
            End If
        Loop
        'Create union query
        For Each qry In CurrentDb.QueryDefs
            If qry.Name = "Q-" & QueryRs![ForeignName] Then
               DoCmd.DeleteObject acQuery, "Q-" & QueryRs![ForeignName]
            End If
        Next qry
        Set QueryDef = CurrentDb.CreateQueryDef("Q-" & QueryRs![ForeignName], SQLText)
        QueryDef.Close
        Set QueryDef = Nothing
        QueryRs.MoveNext
        TableRs.Close
        Set TableRs = Nothing
    Loop
Else
    MsgBox "No files are linked currently"
End If

QueryRs.Close

Err_CreateUnionQueries:
    MsgBox "We have an error"
    Set QueryRs = Nothing
    Set TableRs = Nothing
    Exit Sub
End Sub

1 个答案:

答案 0 :(得分:0)

哦,伙计,我是个白痴。发现了问题。当我循环时,我没有将SQLText设置为空,所以它将我对表组的查询追加到最后一个。删除它,现在它按预期工作。谢谢你们的帮助。