Creating Your Own Properties

Earlier, this chapter introduced user-defined properties, which you can use to store and retrieve your own information about an object. DAO is extensible by using these properties. The following function tries to set a property on an object. If the property doesn’t exist in that object’s Properties collection, then the function creates the property and appends it to the collection:

Function SetCustomProperty(obj As Object, strName As String, _
		intType As Integer, varSetting As Variant) As Boolean
	' This procedure attempts to set a property on an object.
	' If the property does not exist in the object's Properties collection,
	' then the procedure creates the object.
	Dim prp As Property
	Const conPropNotFound As Integer = 3270

	On Error GoTo ErrorSetCustomProperty
	' Explicitly refer to Properties collection.
	obj.Properties(strName) = varSetting
	obj.Properties.Refresh
	SetCustomProperty = True

ExitSetCustomProperty:
	Exit Function
    
ErrorSetCustomProperty:
	If Err = conPropNotFound Then

		' Create property, denote type, and set initial value.
		Set prp = obj.CreateProperty(strName, intType, varSetting)
		' Append Property object to Properties collection.
		obj.Properties.Append prp
		obj.Properties.Refresh
		SetCustomProperty = True
		Resume ExitSetCustomProperty
	Else
		MsgBox Err & ": " & vbCrLf & Err.Description
		SetCustomProperty = False
		Resume ExitSetCustomProperty
	End If
End Function

For example, to create a property called DateLastModified on each table in a database, you may call this function from the following code, which creates the property on each table that isn’t a system object. In this example, strDbPath is the path to the database:

Dim dbs As Database, tdf As TableDef
' Define constant to specify system object.
Const conSystemObject As Long = -2147483648

Set dbs = OpenDatabase(strDbPath)
For Each tdf In dbs.TableDefs
	' Check to see whether table is system object or hidden.
	If Not (tdf.Attributes And conSystemObject) = conSystemObject Then
		If Not (tdf.Attributes And dbHiddenObject) = dbHiddenObject Then
			' Set property.
			SetCustomProperty tdf, "DateLastModified", dbDate, Now
		End If
	End If
Next tdf

Of course, simply adding a property doesn’t automatically update and maintain it. In the previous example, the DateLastModified property is added to the TableDef object, but that’s the extent of what the code does. Your application must programmatically update the value of this property when appropriate.