View Full Version : How to add a new record in a table by code or macro?


WilliamQian
11-08-2007, 01:57 PM
I have a simple table of Customer names. It's as simple as two fields involved:

CustomerID
CustomerName

How can I use VBA code or macro to add a new record to this table? I'm a newbie, so if possible, please provide a few lines of example codes. Thanks.

CraigDolphin
11-08-2007, 02:02 PM
dim strSQL as string

strSQL = "Insert into tblCustomer ([CustomerName]) Values ('" & Inputbox("Please tell me a name to add to the table") & "');"
docmd.runSQL strSQL

or you could define a variable that holds the name and use that in place of the input box...

or use a value currently in the text control instead of the input box. eg ... & [Forms]![FormNameHere].[txtboxNameHere] & ...

whatever floats your boat

WilliamQian
11-09-2007, 11:34 AM
This is great! It works. Thanks, Dolphin. :)

CraigDolphin
11-09-2007, 11:49 AM
You're welcome. :)

WilliamQian
11-09-2007, 12:00 PM
I also learned a lot from your other posts. They solved my problems on ComboBox. Here's my code. When an user input a customer name that is not in my customer table, a message box will pop up and ask if the user wish to add it to the list. If yes, a new record will be added to the customer table. Done!

It works just perfectly. Thanks again.

Private Sub CUSTOMER_NotInList(NewData As String, Response As Integer)

Dim ctl As Control
Dim strSQL As String
' Return Control object that points to combo box.
Set ctl = Me.CUSTOMER

' Prompt user to verify they wish to add new value.
If MsgBox("Customer '" & ctl.Text & "' is not in the list. Add it?", _
vbOKCancel) = vbOK Then
strSQL = "Insert into Customer ([CompanyName]) Values ('" & ctl.Text & "');"
DoCmd.RunSQL strSQL
Response = acDataErrAdded
End If

End Sub

CraigDolphin
11-09-2007, 12:07 PM
Again, you're welcome. And thanks for using the search function to find what you need before asking. :)

boblarson
11-09-2007, 12:18 PM
Again, you're welcome. And thanks for using the search function to find what you need before asking. :)

A Big AMEN to that! That is a trait that is seems to be seldom seen here, but is greatly appreciated.