出于安全原因,我想在我的数据库中创建一个自毁的按钮。我需要修改我的代码,以便它可以在我的所有表,查询,表单,报表,模块中循环并删除它们。如果发生错误,请转到下一个。
现在我使用以下代码,这是一个例子:
On error Resume Next
DoCmd.DeleteObject acTable, "tblExtra"
DoCmd.DeleteObject acTable, "tblFinances"
DoCmd.DeleteObject acTable, "tblHealth"
....
正如您将看到的,我正在为要删除的每个项目使用DoCmd.DeleteObject。
谢谢。
答案 0 :(得分:6)
此代码将删除所有对象,沿途可能存在错误,因此如果需要,您仍应使用错误恢复。它关闭对象然后删除:
Dim obj As AccessObject
For Each obj In CurrentProject.AllReports
Debug.Print "Deleting " & obj.Name
DoCmd.Close acReport, obj.Name, acSaveNo
DoCmd.DeleteObject acReport, obj.Name
Next
For Each obj In CurrentProject.AllForms
Debug.Print "Deleting " & obj.Name
DoCmd.Close acForm, obj.Name, acSaveNo
DoCmd.DeleteObject acForm, obj.Name
Next
For Each obj In CurrentData.AllTables
If obj.Name Not Like "MSys*" then
Debug.Print "Deleting " & obj.Name
DoCmd.Close acTable, obj.Name, acSaveNo
DoCmd.DeleteObject acTable, obj.Name
End If
Next
For Each obj In CurrentData.AllQueries
Debug.Print "Deleting " & obj.Name
DoCmd.Close acQuery, obj.Name, acSaveNo
DoCmd.DeleteObject acQuery, obj.Name
Next
供您参考,如果您想添加更多要删除的对象,以下是CurrentData中的对象:
https://msdn.microsoft.com/en-us/library/office/ff823195.aspx
以下是CurrentProject中的对象:
https://msdn.microsoft.com/en-us/library/office/ff835979.aspx
答案 1 :(得分:1)
对于Access 2016,Graham的答案在删除对象时随机失败(自动化错误)。
从索引的最后到第一个删除对象更安全。 如果您擦除任何重要对象,则checkonly参数仅用于测试目的。
我已经在Access 2016 MSO(16.0.8431.2110)32位中测试了这两种解决方案。
Public Sub deleteObjects(Optional ByVal CheckOnly As Boolean = True)
Dim obj As AccessObject
Dim i As Long
With CurrentProject
For i = .AllReports.count - 1 To 0 Step -1
Set obj = .AllReports(i)
Debug.Print "Deleting " & obj.Name
If Not CheckOnly Then
DoCmd.Close ObjectType:=acReport, ObjectName:=obj.Name, Save:=acSaveNo
DoCmd.DeleteObject acReport, obj.Name
End If
Next
For i = .AllForms.count - 1 To 0 Step -1
Set obj = .AllForms(i)
If obj.Name <> "myImportantForm" Then
Debug.Print "Deleting " & obj.Name
If Not CheckOnly Then
DoCmd.Close ObjectType:=acForm, ObjectName:=obj.Name, Save:=acSaveNo
DoCmd.DeleteObject acForm, obj.Name
End If
End If
Next
For i = .AllModules.count - 1 To 0 Step -1
Set obj = .AllModules(i)
If obj.Name <> "myImportantModule" Then
Debug.Print "Deleting " & obj.Name
If Not CheckOnly Then
DoCmd.DeleteObject acModule, obj.Name
End If
End If
Next
End With
With CurrentData
For i = .AllQueries.count - 1 To 0 Step -1
Set obj = .AllQueries(i)
Debug.Print "Deleting " & obj.Name
If Not CheckOnly Then
DoCmd.Close ObjectType:=acQuery, ObjectName:=obj.Name, Save:=acSaveNo
DoCmd.DeleteObject acQuery, obj.Name
End If
Next
For i = .AllTables.count - 1 To 0 Step -1
Set obj = .AllTables(i)
If Not obj.Name Like "MSys*" Then
Debug.Print "Deleting " & obj.Name
If Not CheckOnly Then
DoCmd.Close ObjectType:=acTable, ObjectName:=obj.Name, Save:=acSaveNo
DoCmd.DeleteObject acTable, obj.Name
End If
End If
Next
End With
End Sub