There is bug in MS Access that even if you follow the instructions from the official website of MS still you won't be able to "create" and "edit" controls at "run-time".
I found one way to go around this bug (witch is a combination of solutions I got from others).
Non working solution: Don't tray to define a variable to create the object:-
Sample 1:
-
DoCmd.OpenForm "Form1", acDesign
-
Dim t as TextBox
-
set t = CreateControl("Form1", acTextBox)
-
t.FontName = "Arial" 'Any sample as test.
-
.ForeColor = vbRead 'Any sample as test.
-
.DefaultValue = 10 'Any sample as test.
-
'etc...
-
This way will give you error (by the way it is what you get from MS official site).
If you use the "With" it will work, but....
Sample 2:
-
DoCmd.OpenForm "Form1", acDesign
-
With CreateControl("Form1", acTextBox)
-
.FontName = "Arial" 'Any sample as test.
-
.ForeColor = vbRead 'Any sample as test.
-
.DefaultValue = 10 'Any sample as test.
-
'etc...
-
End With
-
This way Won't give you any error (bug free) But....
You won't be able to edit it later through the code; because we didn't use an object or variable to hold it or point to it (as in Sample 1).
My solution is: To use the name of the control to call it using "Controls()", and that is after useing "With" to create the control.:-
Sample 3:
-
DoCmd.OpenForm "Form1", acDesign
-
Dim strName as string
-
With CreateControl("Form1", acTextBox)
-
.FontName = "Arial" 'Any sample as test.
-
.ForeColor = vbRead 'Any sample as test.
-
.DefaultValue = 10 'Any sample as test.
-
' etc...
-
strName = .Name 'Get the default name from the control (or you can give one).
-
End With
-
'And to be able to edit it later use the name you got in the previous lines.
-
Me.Controls(strName).FontName = "Times New Roman" 'Any sample as test.
-
Me.Controls(strName).ForeColor = vbGreen 'Any sample as test.
-
Me.Controls(strName).DefaultValue = 20 'Any sample as test.
-
' etc...
-