删除 Table 或查询是否存在的函数

Function To Delete Table Or Query If Exists

我正在尝试使用一个函数来检查是否将 table/query 传递给函数然后将其删除。我的问题是,当它遇到这行语法时

If TableExists(CStr(tableArray)) Then

我收到类型不匹配错误。但是,如果我将语法更改为 If TableExists(CStr(amx)) Then,则值为 0,因此 table/query 仍未删除。将 table 名称数组和查询名称传递给函数并删除它们(如果它们存在)的适当语法是什么?

    Function DeleteTables()
   tableArray = Array("Table1", "Table2", "Table3", "Table4")   
   queryArray = Array("Query1", "Query2", "Query3")

    For amx = LBound(tableArray) To UBound(tableArray)
        If TableExists(CStr(tableArray)) Then
            With db.TableDefs
                .Delete CStr(tableArray)
                .Refresh
            End With
        End If
   Next

   For qdi = LBound(queryArray) To UBound(queryArray)
        If TableExists(CStr(queryArray)) Then
            With db.QueryDefs
                .Delete CStr(queryArray)
                .Refresh
            End With
        End If
   Next
End Function
Public Function TableExists(strName As String) As Boolean

   On Error GoTo HandleErr

   Dim db As DAO.Database, tDef As DAO.TableDef

   Set db = CurrentDb

   TableExists = False

   For Each tDef In db.TableDefs
      If tDef.Name = strName Then
         TableExists = True
         Exit For
      End If
   Next tDef

   For Each qDef In db.QueryDefs
    If qDef.Name = strName Then
        TableExists = True
        Exit For
    End If
   Next qDef

ExitFunction:
   db.Close
   Set db = Nothing
   Exit Function

HandleErr:
   TableExists = False
   Resume ExitFunction

End Function

Type Mismatch

你就快完成了,你只需要引用你正在循环的数组中的特定项目:

将您当前的代码更改为:

    If TableExists(CStr(tableArray(amx))) Then
        With db.TableDefs
            .Delete CStr(tableArray(amx))
            .Refresh
        End With
    End If

    If TableExists(CStr(queryArray(qdi))) Then
        With db.QueryDefs
            .Delete CStr(queryArray(qdi))
            .Refresh
        End With
    End If

你以后也可以使用For Each循环,它们往往更容易理解。