简体   繁体   English

在VBA中从另一个用户表单设置复选框

[英]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. 我有一个用户窗体,其中包含从1到100的多个复选框。我编写了一些非常简单的代码,以便在您提交表单时,它会创建一个二进制字符串来表示这100个复选框的状态,其中0为false,1为真正。 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. 现在,我想从另一个具有类似二进制字符串的表单中打开该用户窗体,并使用该字符串将复选框的值设置为true或false(适当)。 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 ie where nm = "BusinessRules.CheckBox1" 当我运行上述命令时,出现运行时错误“找不到指定的对象”,并且在进行调试时在代码状态为“ Set c = Controls(nm)”时突出显示了此问题-我可以看到它正在失败在循环的第一轮中,即nm =“ BusinessRules.CheckBox1”

Interestingly if I run the code "Set c = Controls(BusinessRules.CheckBox1)" I get no such issue. 有趣的是,如果我运行代码“ Set c = Controls(BusinessRules.CheckBox1)”,则不会出现此类问题。

Any help would be much appreciated. 任何帮助将非常感激。

Thanks, 谢谢,

Paul. 保罗

I think the BusinessRules is giving you the issue. 我认为BusinessRules可以解决这个问题。 In the Controls collection, there is no Control named "BusinessRules.CheckBox1" , only one named "CheckBox1" within the BusinessRules.Controls collection. 在控件集合中,没有名为"BusinessRules.CheckBox1" "CheckBox1" ,在BusinessRules.Controls集合中只有一个名为"CheckBox1""CheckBox1" 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 假设上面的注释中没有提到其他问题(例如在调用此表单之前已将其关闭),那么这应该可以解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM