MS Access: Drop table if exists in MS Access

I had a scenario to check existance of a specified table in access. If the specified table is available, it should get deleted(drop) or else just go on performing with the rest of the code. This operation should be done when we close the form. So I used Sub Form_Unload and developed the code.
Private Sub Form_Unload(Cancel As Integer)

Dim tbl As TableDef
Dim db As Database
Set db = CurrentDb

For Each tbl In db.TableDefs
If tbl.Name = "FirstTbl" Then
db.Execute "DROP TABLE FirstTbl"
End If
If tbl.Name = "SecondTbl" Then
db.Execute "DROP TABLE SecondTbl"
End If
Next tbl

End Sub
This is one more method using User defined function
Public Function ifTableExists(tablename As String) As Boolean

ifTableExists = False
If DCount("[Name]", "MSysObjects", "[Name] = '" & tablename & "'") = 1 Then
ifTableExists = True
Else
ifTableExists = False
End If

End Function
After creating above UserDefined Function it can be used as
If ifTableExists("MyTable") Then db.Execute "DROP Table MyTable"

No comments:

Post a Comment