Thanks for the compliment, Jerry.
If I understood your original question, you want to initialize some controls
to empty strings and others to numeric zeroes, depending upon their intended
future binding. If this is the case, then perhaps you could modify the code
to examine the *intended* record source first to determine the data types.
Then, if your form's text control names are identical to the recordset's
field names, you could enumerate through them that way.
The code would no longer be suitable for a global module, I don't think, but
you could just place the code into the form's module and it wouldn't be an
issue.
I just worked on this, and it seems to work fine:
=== START OF CODE =================
Private Sub InitControls()
Dim ctl As Control
Dim rs As Recordset
Dim fld As Field
Dim DefVal As Variant
'Examine the intended record source.
Set rs = CurrentDb.OpenRecordset("tblTest", dbOpenDynaset)
'Enumerate through the fields.
For Each fld In rs.Fields
'Use defaults specified in the table def.
If Not fld.DefaultValue = "" Then
DefVal = fld.DefaultValue
Else
'Set the default by the field's data type.
Select Case fld.Type
Case dbBoolean
DefVal = False
Case dbByte, dbCurrency, dbDecimal, dbDouble, _
dbFloat, dbInteger, dbLong, dbNumeric, _
dbSingle
DefVal = 0
Case dbDate, dbTime
DefVal = Now
Case dbMemo, dbText
'Deal with the zero-length attribute.
If fld.AllowZeroLength Then
DefVal = ""
Else
DefVal = Null
End If
End Select
End If
'Set the related control's value.
For Each ctl In Me.Controls
If ctl.Name = fld.Name Then
'Do not attempt to set autonumber field.
If (fld.Attributes And dbAutoIncrField) = 0 Then
ctl = DefVal
Exit For
End If
End If
Next ctl
Next fld
'Close the recordset.
rs.Close
'Destroy the object variable.
Set rs = Nothing
End Sub
=== END OF CODE =================
Jerry said:
Thansk Brian. When I went through your code, I found that the form is
bounded to a recordset. But how about if my form does not have recordsets.
I have a blank form just for input. after finished input, my prgram will
perform validation and update. After update the recordsets will be closed.
In order for the form be available for next input, I want to clear (blank
out) all controls in ther form.
Thanks for your code. It is beautiful. Actually you have given me some
idea to use color for highlight if that control does not pass validation.