Tuesday, February 16, 2016

How to create table in MS ACCESS database using Excel VBA code ?


Before running the code below, we would need to add the reference to Microsoft ActiveX Data Objects 2.x Library in the Excel VBA Editor.


--------------------------------------------------------------------------------------------------------------------------

Sub Create_Test_Table ()

'Define the variables to be used in the VBA code
Dim connectdb  As String, pathdb As String, connObj  As ADODB.Connection

'Assigning the database name and the connection path to the pathdb variable
pathdb = Sheet1.Range("A2").Value

'In the above case the reference is taken from Range A2 of sheet 1, while we can directly add the path in VBA code e.g.
'pathdb = "C:\Users\Default\Desktop\Test.accdb"    

'Connection reference and path
connectdb = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & pathdb & ";"

'Connecting to the database and creating new table
Set connObj = New ADODB.Connection

With connObj
.Open connectdb
.Execute "CREATE TABLE TEST_TABLE ([COL1] text(50) WITH Compression NULL, " & _

                 "[COL2] text(200) WITH Compression NULL, " & _
                 "[COL3] datetime NULL)"
End With

' Table with name "TEST_TABLE" will be added to the database, with 3 columns listed in above code

End Sub

--------------------------------------------------------------------------------------------------------------------------

You can add as many columns you want to add in the above code. This code can be directly copied to Excel VBA editor and executed with few tweaks like:
1. Changing the pathdb
2. Changing the required column names
3. Changing the required table name

If you want to learn about VBA, please visit my blog posts below :



How to use Excel Macro Recorder ?

and

more....

1 comment:

  1. I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post.
    excel vba courses london

    ReplyDelete