For Each Form Control collection iteration

R

rmanchu

guys, what's going on here?
as u can c, some controls r being hit more than once and some not at
all!!!

For Each ctlTD In Forms(varT.Name).Controls
If ctlTD.ControlType = Access.acTextBox _
Or ctlTD.ControlType = Access.acComboBox _
Or ctlTD.ControlType = Access.acCheckBox Then
strTD = ctlTD.ControlSource
Debug.Print strTD 'out res
If Len(strTD) > 0 Then
strTD = Mid$(strTD, InStr(1, strTD, "_"))
strTD = frmPrefix & strTD
ctlTD.ControlSource = strTD
ctlTD.Name = strTD
ctlTD.Controls(0).Name = strTD & "_Label"
End If
End If
Next ctlTD

Output:
BN_OwnerStaff
BN_OwnerSection
BN_TimeStamp
BN_Progress
BN_Rejected
BN_ReqIdent
BN_Phone
BN_ReqAddressCD
BN_RegNameE
BN_CollDate
BN_OwnerSection
BN_Progress
BN_ReqIdent
BN_ReqAddressCD
BN_CollDate
BN_Progress
BN_ReqAddressCD
BN_Progress
BN_Progress
 
T

TC

You're getting the same /controlsource/ printed more than once - not
the same control. Although it's unusual - and usually, misconceived -
there's nothing to stop you giving the same controlsource to many
controls.

Change this: Debug.Print strTD

to this: Debug.Print ctlTD.name, strTD

and you'll see what I mean.


Here's another change to make your coding easier:

Change this:

If ctlTD.ControlType = Access.acTextBox _
Or ctlTD.ControlType = Access.acComboBox _
Or ctlTD.ControlType = Access.acCheckBox Then
(do stuff)
Endif

to this:

SELECT CASE ctlTD.ControlType
CASE acTextBox , acComboBox , acCheckBox
(do stuff)
END SELECT

Same result, but much easier reading!

HTH,
TC (MVP Access)
http://tc2.atspace.com
 
R

rmanchu

its the same for Control.Name

it seems to me that

the "For Each" construct is invalid if the controls name is changed
within the ForEach loop!

by invalid i mean: some controls are not returned and others are
returned multiple times. the total count does not seem to match either!

is this expected?

riyaz
 
T

TC

Ack!! Sorry, I didn't notice that you were changing the name of the
controls!

If you change the properties of a collection member, this can disrupt
an enumeration of that collection. This is a well known thing.

One solution is to copy the control names somewhere, and then enumerate
the copied names - not the originals. So:

' copy the current names.
dim cTmp as collection
for each ctl in me.controls
cTmp.add ctl.name, ctl.name
next

' enumerate the copied names.
dim v as variant
for each v in cTmp
set ctl = me.controls(v)
' now you can do what you want, with that control.
next

HTH,
TC (MVP Access)
http://tc2.atspace.com
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top