Setting properties to Access field using VBA

I want to set the format properties of an Access table field using vba. I try with the following code, but get an error at the line " myField.Properties(PropertyName) = PropertyValue"
What needs to be changed?


Public Function fStartup

      Call SetDAOProperty("Tablename", "Fieldname", "Format", "000000-0000")

 End Function

Function SetDAOProperty(Optional mTable As String, Optional mfield As String, Optional PropertyName As String, Optional PropertyValue As String)
    Dim db As DAO.Database
    Dim myTable As DAO.TableDef
    Dim myField As DAO.Field
    Set db = CurrentDb()
    Set myTable = db.TableDefs(mTable)
    Set myField = myTable.Fields(mfield)
    myField.Properties(PropertyName) = PropertyValue

    SetDAOProperty = True
    Exit Function

End Function
Who is Participating?
DatabaseMX (Joe Anderson - Microsoft Access MVP)Connect With a Mentor Database ArchitectCommented:
Here you go:

    Dim db As DAO.Database, prp As DAO.Property
    Set db = CurrentDb
    With db.TableDefs("MyTable").Fields("MyField")
            'On Error Resume Next ' This is needed one prop is created
            Set prp = .CreateProperty("Format", dbText, Chr(34) & "000000-0000" & Chr(34))

            If Err.Number = 0 Or Err.Number = 3367 Then
                 'do nothing  3367 means Property already exists
                MsgBox "error " & Err.Number & "  " & Err.Description
                Exit Function
            End If
            .Properties.Append prp
    End With
FagerbergDellbyAuthor Commented:
Super, works like a charm. Many thanks!
DatabaseMX (Joe Anderson - Microsoft Access MVP)Database ArchitectCommented:
You are welcome ...

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.