check if form exists

Jaye7

Registered User.
Local time
Tomorrow, 09:11
Joined
Aug 19, 2014
Messages
205
I have the following vba to check if a table exists, but I can not find on the net how to check if a form exists, I tried to modify this script but there does not seem to be a formdef

Code:
 Sub table_Exists()
  Dim dbs As Database
 Dim tbl As TableDef
 Dim dbsExist As Object
 Dim tablename As String
 tablename = "Table2"   ' Your Table Name
 Dim exists As String
 
     Set dbs = CurrentDb
     Set dbsExist = dbs.TableDefs
 '--------------------------------------------------------------
 ' Search for AccessObject objects in AllTables collection.
 
     For Each tbl In dbsExist
         If tbl.Name = tablename Then
             MsgBox "Table Exists"
             exists = True
             GoTo Part2
             
         End If
     Next tbl
 Part2:
If exists = "True" Then
Exit Sub
Else
MsgBox "Table Does Not Exists"
End If
      Set dbsExist = Nothing ' Clean up
 End Sub
 
Forms are located in CurrentProject.AllForms
 
Are you able to provide the script that I would need as I am not sure how to modify it.
 
Try changing:
Dim tbl As TableDef
to
Dim tbl As Object

Set dbsExist = dbs.TableDefs
to
Set dbsExist = CurrentProject.AllForms

And see what happens.

If it works then change the variable names and strings to something that makes more sense.
 
You can use MSysObjects instead. Put the following into a query:
Code:
SELECT * FROM MSysObjects;
... that will give you a list of all the objects (i.e. tables, forms, etc) in the database. Then enter criteria to filter it down to only the forms.
 
rather than checking all the tabledefs or forms, you can test one directly. however this throws an error if the tabledef does not exist

so

Code:
 function tableexists(tblname as string) as boolean
 on error goto fail
 tabledefexists = currentdb.tabledef(tblname).name = tblname
 exitfunction
  
 fail:
 tabledefexists=false
 end function
the same idea works for formexists. note that currentproject.allforms just tests whether the form exists at all. you need a slightly different method to see if the form is currently open.
 
rather than checking all the tabledefs or forms, you can test one directly. however this throws an error if the tabledef does not exist
Pretty much what Jaye7 is doing in his first post and what Galaxiom further revised in his second post.
 

Users who are viewing this thread

Back
Top Bottom