Back To Top


MS Access VBA Update Field Function For versions 2000, 2002, 2003, 2007

Go here To Update a field in the Query Builder.
Go here To Get all Fields in a Table.
Go here To Check if Table exists in VBA.
Go here To Update a Field From a Joined Table in VBA.
Go here To Rename a Field in VBA.

 

The VBA Update Sample is available for download here in a zipped MS Access Database. The below picture (click to enlarge) shows the Single form and module.

MS Access Form Using VBA to Update a field. 

The Actual VBA Code to Update a Field within a Table, you should be able to copy/paste right into a module:




Function
updateField(TableName As String , FieldName As String , _
      WhereField
As String , WhereStrValue As String , _
      strValue
As String ) As Boolean

  
' Updates a Field with a given strValue where another WhereStrValue exists in a field
   ' in table TableName.
   ' Accepts
   ' TableName: Name of table in which the field is located
   ' FieldName: Name of the field to update
   ' WhereField: Name of the field with criteria
   ' WhereStrValue: Given Criteria
   ' strValue: String to update the field to
   ' Returns True on success, false otherwise
   'USAGE: updateField "TABLENAME", "FIELDNAME", "WHEREFIELD", "WHERESTRVALUE", "STRVALUE"
  
On Error GoTo errhandler
  
Dim strSql As String , Db As dao.Database


  
'Create the Update SQL Code from our Four String Values
   'Create the Update SQL Code from our Four String Values
  
strSql = "UPDATE " & TableName & " SET " & TableName & _
        
"." & FieldName & "='" & strValue & "' WHERE ((([" & _
         TableName
& "]." & WhereField & ")='" & WhereStrValue & "'));"


  
'Print the SQL so we can paste into the query build if there are errors
  
Debug.Print strSql
  
'Use Current Database
  
Set Db = CurrentDb()


  
'Run the SQL Query
  
Db.Execute strSql

  
'If no errors return true
  
updateField = True
ExitHere:

  
Set Db = Nothing

  
'Notify the user the process is complete.
  
MsgBox "Update Complete"
  
Exit Function
errhandler:
  
'There is an error return false
  
updateField = False
   With Err
     
MsgBox "Error " & .Number & vbCrLf & .Description, _
            vbOKOnly
Or vbCritical, "updateField"
  
End With
   Resume
ExitHere
End Function

 

For the above VBA Update Function in an usable Form with Update Button, download the Sample database in ZIP format. The sample includes 100 records in which to test on.

You may post this tutorial on your website or in a forum. If you do please maintain a Link to Eraseve AP.



For further MS Access tutorials go here: MS Access tutorials

Follow the Set Autonumber Field with VBA Link to Set a Field to Autonumber.

To Change a field’s data type in VBA go here.

 

Did you find what you were looking for?
What would you suggest?
mail@eraserve.com
Your Name:
Your Message:
Your Email:

    

 

Custom Search