Checking table existence

  • Thread starter Thread starter tt
  • Start date Start date
T

tt

I need to delete a a table from my database using visual
basic. The problem is that if the table has already been
deleted (by running the code, but for some reason it can't
complete), the next time there is no table to delete and
an error is reported. How do I check that the table exists
before I run the command to delete it.
 
Why not trap for the error and Resume Next when the error "Table does not
exist" is raised from your code? Might look like:

Public Sub YourSub()
On Error GoTo errHandleHere
' Do all kinds of things and stuff
...
' Till finally time to drop the table
DoCmd.RunSql "Drop Table YourTableName"
' Do other stuff till done
...
Exit Sub
errHandleHere:
if err.num = 3376 then Resume Next
' Other code here that handles other errors
End Sub

Ron W
 
As an alternative to the method below (I don't like my code to trigger
errors if it is possible to avoid it to make debugging easier).

Create a TableExists function. The example below uses DAO so make sure you
have a DAO reference set in Tools/References.

Public Function TableExists(strTableName as String) as Boolean

dim tdf as dao.tabledef

TableExists = False

for each tdf in currentdb.tabledefs
if tdf.name = strTableName then
TableExists = True
Exit For
end if
next

End Function
 
Assuming Access 2000 or later, why not use the 'AllTables' collection, which
does not depend on either DAO *or* ADO ...

Public Function IsTable1(ByVal strTableName As String) As Boolean

Dim aob As AccessObject

For Each aob In CurrentData.AllTables
If aob.Name = strTableName Then
IsTable1 = True
Exit For
End If
Next aob

End Function

If you really want to use ADO, you'll have to add a reference to the ADOX
(Microsoft ADO Ext. 2.x for DDL and Security) object library. If you're
deploying an application outside of your own organisation, this can be
problematic because there is a high risk of the user having a different
version of ADOX installed, but for in-house deployment it may be OK ...

Public Function IsTableADOX(ByVal strTableName As String) As Boolean

Dim cat As ADOX.Catalog
Dim tbl As ADOX.Table

Set cat = New ADOX.Catalog
cat.ActiveConnection = CurrentProject.Connection
For Each tbl In cat.Tables
If tbl.Name = strTableName Then
IsTableADOX = True
Exit For
End If
Next tbl
End Function

--
Brendan Reynolds (MVP)
http://brenreyn.blogspot.com

The spammers and script-kiddies have succeeded in making it impossible for
me to use a real e-mail address in public newsgroups. E-mail replies to
this post will be deleted without being read. Any e-mail claiming to be
from brenreyn at indigo dot ie that is not digitally signed by me with a
GlobalSign digital certificate is a forgery and should be deleted without
being read. Follow-up questions should in general be posted to the
newsgroup, but if you have a good reason to send me e-mail, you'll find
a useable e-mail address at the URL above.
 
Back
Top