Code: write values from controls to unbound form fields

Office for Mere Mortals
Your beginners guide to the secrets of Microsoft Office
Invalid email address
Tips and help for Word, Excel, PowerPoint and Outlook from Microsoft Office experts.  Give it a try. You can unsubscribe at any time.  Office for Mere Mortals has been running for over 20 years, we've never, ever revealed or sold subscriber details.  Privacy policy

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)


   With rstData



      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

         End If

      Next ctl




   End With


   strTitle = "Information"

   strPrompt = "A new record has been added."

   MsgBox prompt:=strPrompt, _

      buttons:=vbInformation + vbOKOnly, _




   Set rstData = Nothing

   Exit Sub



   MsgBox "Error No: " & Err.Number _

      & " in AddRecord procedure; " _

      & "Description: " & Err.Description

   Resume ErrorHandlerExit


End Sub


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.