Avatar of Peter Chan
Peter Chan
Flag for Hong Kong asked on

Access issue

Hi,
In VBA, how to check if one table is existing or not in Access DB? And how to also duplicate existing table to another in Access DB? 
Microsoft AccessVBAMicrosoft ExcelMicrosoft Office

Avatar of undefined
Last Comment
als315

8/22/2022 - Mon
Fabrice Lambert

This is doable with the help of  generic function.
Tables are represented by the TableDefs collection who's table name is the key.
So to check if the key is present, we can just attempt to retrieve it, if it fail, the table do not exist, and an error will be raised. We intercept it with an error handler:
Public Function ExistInCollection(ByRef Col as Object, ByVal Key As String) As Boolean
    ExistInCollection = ExistInCollectionByVal(Col, Key) Or ExistInCollectionByRef(Col, Key)
End Function

Private Function ExistInCollectionByVal(ByRef Col AsObject, ByVal Key As String) As Boolean
On Error Goto Error
    Dim Item As Variant
    Item = Col(Key)
    ExistInCollectionByVal = True
Exit Function
Error:
    ExistInCollectionByVal  = False
End Function

Private Function ExistInCollectionByRef(ByRef Col AsObject, ByVal Key As String) As Boolean
On Error Goto Error
    Dim Item As Variant
    Set Item = Col(Key)
    ExistInCollectionByRef = True
Exit Function
Error:
    ExistInCollectionByRef = False
End Function

Open in new window


To use it, just pass the TableDefs collection and table name arguments to the function:
Public Sub Test()
    Const TableName As String = "myTable"
    Dim Db As DAO.Database
    Set Db = CurrentDb

    If Not(ExistInCollection(Db.TableDefs, TableName) Then
        '// The table Do Not exist, do whatever you like here.
    Else
        '// The table exist
    End If
End Sub

Open in new window

Peter Chan

ASKER
Hi,
Thanks a lot. How to run "select * into otherTab from ..." against Access DB?
Fabrice Lambert

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Peter Chan

ASKER
Sorry, I do not see the way to duplicate one table, from that.

Can you also advise to code below?

Fabrice Lambert

It is just a matter of running a query:
SELECT *
INTO Table2
FROM [C:\Test\Test.accdb].Table1;

Open in new window

als315

Function for testing table existance:
Public Function TblExists(ByVal strTableName As String) As Boolean
    Dim tblN As Object
    TblExists = False
    For Each tblN In CurrentDb.TableDefs
        If tblN.Name = strTableName Then
            TblExists = True
            Exit For
        End If
    Next tblN
End Function

Open in new window


You can also use docmd for object copy
Sub tst()
If TblExists("Table2") Then
' Delete Table2
    DoCmd.DeleteObject acTable, "Table2"
End If
' Copy Table1 toTable 2 in CurrentDB
DoCmd.CopyObject , "Table2", acTable, "Table1"
End Sub

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Peter Chan

ASKER
Fabrice,
Do you see file below? Can you help?
1f.png
Peter Chan

ASKER
Als,
I've got attached error, like1g.png

due to For Each line below.
Public Function TblExists(ByVal strTableName As String) As Boolean
    Dim tblN As Object
    TblExists = False
    For Each tblN In Adb.TableDefs
        If tblN.Name = strTableName Then
            TblExists = True
            Exit For
        End If
    Next tblN
End Function


    Dim Adb As Object: Set Adb = CreateObject("Access.Application")
    Call Adb.OpenCurrentDatabase(F1)
    Adb.Visible = False

Open in new window


als315

Try other version of function (without objects):
Public Function TblExists(ByVal strTableName As String) As Boolean
TblExists = False
If Not IsNull(DLookup("Name", "MSysObjects", "Name = " & Chr(34) & strTableName & Chr(34) & " AND Type = 1")) Then TblExists = True
End Function

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Peter Chan

ASKER
I got

Sub or Function not defined

to DLookup in your code.


als315

Could you make screenshot with references (VBA Editor Tools-References)?
references
Peter Chan

ASKER
Yes, I checked that OLE Automation was already selected in the reference.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
aikimark

als315

You had to have Microsoft Access XX Object library checked
Peter Chan

ASKER
Sorry, which is the option per attached file?1k.png
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
als315

Look for "Microsoft Access 16.0 Object Library"
als315

Try attached sample
Database2.accdb
ASKER CERTIFIED SOLUTION
Fabrice Lambert

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Peter Chan

ASKER
Many thanks.
When writing to Access DB, is details of current active worksheet going to the table having same name of current work sheet?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Fabrice Lambert

Nope, you never mentionned such detail.
It goes to T1 table.

The function I wrote can write data to an,y table. Adjust to fit your needs.
als315

Are you trying to copy table from Excel VBA?