功能删除表或查询如果存在

时间:2017-12-05 14:03:08

标签: vba ms-access access-vba ms-access-2013

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

If TableExists(CStr(tableArray)) Then

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

    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

1 个答案:

答案 0 :(得分:2)

你几乎就在那里,你只需要参考你正在循环的数组中的特定项目:

将您当前的代码更改为:

    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循环,它们往往更容易理解。