paul frith
paul frith

Reputation: 633

Setting CheckBoxes from another userform in VBA

I have a userform which contains a number of checkboxes from 1 to 100. I have written some very simple code so that when you submit the form it creates a binary string that represents the state of those 100 checkboxes, where 0 is false and 1 is true. The code to do this is here:

Private Sub BusRulesSubmit_Click()
 Dim myBinaryString As String
 Dim nm As String
 Dim c As Control

 For busRuleIdx = 1 To 100
  nm = "CheckBox" & busRuleIdx
  Set c = Controls(nm)
  If c.Value = True Then
   myBinaryString = myBinaryString & "1"
  Else
   myBinaryString = myBinaryString & "0"
  End If
 Next

 msgBox myBinaryString
End Sub

I now want to open this Userform from another form, where I have a similar binary string, and use this string to set the values of the checkboxes to true or false as appropariate. However I am having issues when setting my control. The code is here:

Private Sub populateBusRules()
 Dim c As Control
 Dim myBRBinary As String
 myBRBinary =    "000000000011100000000000000000000000000000000000000000000000000000000010000000000000000000000000000"

 For busRuleIdx = 1 To 100
  nm = "BusinessRules.CheckBox" & busRuleIdx
  Set c = Controls(nm)
  If Mid(myBRBinary, buRuleIdx - 1, 1) = 1 Then
   c.Value = True
  Else
   c.Value = False
  End If
 Next
End Sub

When I run the above, I get a runtime error "Could not find the specified object" and when going to debug it highlights this problem where the code states "Set c = Controls(nm)" - and I can see that it is failing in the first round of the loop i.e. where nm = "BusinessRules.CheckBox1"

Interestingly if I run the code "Set c = Controls(BusinessRules.CheckBox1)" I get no such issue.

Any help would be much appreciated.

Thanks,

Paul.

Upvotes: 0

Views: 387

Answers (1)

RGA
RGA

Reputation: 2607

I think the BusinessRules is giving you the issue. In the Controls collection, there is no Control named "BusinessRules.CheckBox1", only one named "CheckBox1" within the BusinessRules.Controls collection. Assuming there aren't other issues mentioned in the comments above (like the form being closed before this is called), then this should fix your issue

Upvotes: 1

Related Questions