If you have an unbound form, and need a quick and convenient way to write values from its controls to the appropriate fields, instead of listing every field by name, you can use this procedure, based on the assumption that each control that contains a value to be written to a field has a name that consists of the appropriate 3-letter LNC prefix plus the field name, so that (for example) txtCustomerID’s value will be written to the CustomerID field, cboOffice’s value will be written to the Office field, and so on. Here is the procedure, which can be called from a Save Record button on the unbound form:
Public Sub AddRecord(frm As Access.Form)
On Error GoTo ErrorHandler
Set rstData = CurrentDb.OpenRecordset("tblData", dbOpenDynaset)
For Each ctl In frm.Controls
If ctl.ControlType = acTextBox Or ctl.ControlType = _
acComboBox Or ctl.ControlType = acCheckBox Then
varValue = ctl.Value
strFieldName = Mid(ctl.Name, 4)
'Debug.Print "Field name: " & strFieldName
'Debug.Print "Field value: " & varValue
strTitle = "Information"
strPrompt = "A new record has been added."
MsgBox prompt:=strPrompt, _
buttons:=vbInformation + vbOKOnly, _
Set rstData = Nothing
MsgBox "Error No: " & Err.Number _
& " in AddRecord procedure; " _
& "Description: " & Err.Description
The Debug.Print statements can be used (just remove the apostrophe) for help in figuring out problems; sometimes it is necessary to exclude a specific control, such as a text box used for a label.
Office Watch has the latest news and tips about Microsoft Office. Independent since 1996. Delivered once a week.