Access VBA Create Table (Simplified)

This post is an answer to someone else who wanted to create a table and field names based on form inputs.

So I simplified a past post:

https://vbahowto.com/how-to-create-a-table-in-access-using-sql-and-vba/

Here are the form inputs:

…and when you click the button, the following code runs:

Private Sub btnCreateTable_Click()
    CreateNewTable
    
    MsgBox "Table Created. (Press F5 on your keyboard to view it in the DB window)"
    
End Sub

Public Function CreateNewTable() As Boolean
  
    'create the new access table based on the form parameters:
    
    'use the current database and execute the Create Table SQL command
    DBEngine(0)(0).Execute "CREATE TABLE " & Nz(Me.txtTableName, "NoName") & " (ID COUNTER CONSTRAINT ID PRIMARY KEY, " & _
        Nz(Me.txtFieldName1, "NA1") & " CHAR(255) NOT NULL, " & _
        Nz(Me.txtFieldName2, "NA2") & " CHAR(255) NOT NULL, " & _
        Nz(Me.txtFieldName3, "NA3") & " CHAR(255) NOT NULL, " & _
        Nz(Me.txtFieldName4, "NA4") & " CHAR(255) NOT NULL, " & _
        Nz(Me.txtFieldName5, "NA5") & " CHAR(255) NOT NULL, " & _
        Nz(Me.txtFieldName6, "NA6") & " CHAR(255) NOT NULL)"

    'refresh the current db tables
    DBEngine(0)(0).TableDefs.Refresh

    CreateNewTable = True

End Function

…and a table is produced…

Let me know if you have any questions.




By the way, if you got or are getting value from the VBA information, please give me a tip, thanks!


These posts may help answer your question too...

How To Escape Apostrophe In SQL Update Query

If you are looping a table with thousands of records, you’ll probably run into at least one that has an apostrophe in the field name. Like “Mike’s” or “M’cormick”, or something else. Anyway, here is one way to escape the string when you are doing your update query. Option Compare Database Sub YDriveLoop() ‘4/23/24 erik@loeblcomservices.com […]

How To Make An Access Form Time Picker

Here is a relatively easy way to select times for your time entry text boxes. It’s a reusable form that allows you to pick a time from an Access form. There are probably different ways to do this but here is the way I would do it. On the form that has the time fields, […]

How To Parse A Flat File In Excel VBA

In another post I demonstrated how to access a file on your computer using the MS Office Library. Here it is if you don’t know what I’m talking about. In this post, I am going to show you how to access the file and load it into your spreadsheet. I will do the same thing […]

How to pick a file to load In VBA

Picking a file to load in your Microsoft App is a very important skill to know. In this blog post you will see how to do it. First you need to set a reference to the MS office object library From VBE editor –> select Tools > MS office object library (click check mark) Sub […]

Previous Post

Why Does My Query Change Like To Alike?

Next Post

MS Access FilterOn Error (Solution)