用于检查 MS ACCESS 上是否存在表的 VBA 脚本,如果存在则删除
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42059223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA Script to check if table exist on MS ACCESS, Delete if it does
提问by user-DY
I need to implement a check to see if TableA exists, if it does, drop the entire table. If it doesn't, i will create the table. I couldn't really find out if this is possible to implement on VBA / MS Access.
我需要执行检查以查看 TableA 是否存在,如果存在,则删除整个表。如果没有,我将创建表。我真的不知道这是否可以在 VBA/MS Access 上实现。
In SQL we can use:
在 SQL 中,我们可以使用:
DROP TABLE IF EXISTS dbo.TableA
Anybody has any idea how this can be implemented? Thank you!
任何人都知道如何实现这一点?谢谢!
采纳答案by Parfait
Consider using the TableDefscollection where you iterate through items and conditionally drop or create using same DDL SQL statements passed in code.
考虑使用TableDefs集合,在其中迭代项目并使用在代码中传递的相同 DDL SQL 语句有条件地删除或创建。
Dim db As Database
Dim tbldef As TableDef
Set db = CurrentDb
For each tbldef in db.TableDefs
If tbldef.Name = "TableName" Then
db.Execute "DROP TABLE " & tbldef.Name, dbFailOnError
End if
Next tbldef
db.Execute "CREATE TABLE TableName (...rest of SQL...);", dbFailOnError
' UNINITIALIZE OBJECTS
Set tbldef = Nothing
Set db = Nothing
回答by C Suttle
There is a much easier way to do this than the code above.
有一种比上面的代码更简单的方法来做到这一点。
On Error Resume Next
currentdb.execute "DROP TABLE TABLENAME;"
On Error Goto 0
What this does is tries to delete the table and skips the line if an error is generated because the table does not exists. Only 3 lines and runs faster.
这样做是尝试删除表并在由于表不存在而生成错误时跳过该行。只有 3 行,运行速度更快。