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

Setting CheckBoxes from another userform in VBA

我有一个用户表单,其中包含从 1 到 100 的多个复选框。我编写了一些非常简单的代码,因此当您提交表单时,它会创建一个二进制字符串来表示这 100 个复选框的状态,其中 0为假,1 为真。执行此操作的代码在这里:

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

我现在想从另一个表单打开此用户表单,其中我有一个类似的二进制字符串,并使用此字符串将复选框的值设置为适当的 true 或 false。但是我在设置控件时遇到问题。代码在这里:

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

当我 运行 上面的内容时,我得到一个 运行 时间错误 "Could not find the specified object" 并且在调试时突出显示代码指出 "Set c = Controls(nm)" 的这个问题 - 和我可以看到它在循环的第一轮失败,即 nm = "BusinessRules.CheckBox1"

有趣的是,如果我 运行 代码 "Set c = Controls(BusinessRules.CheckBox1)" 我没有遇到这样的问题。

如有任何帮助,我们将不胜感激。

谢谢,

保罗.

我认为 BusinessRules 是您遇到的问题。在 Controls 集合中,没有名为 "BusinessRules.CheckBox1" 的控件,在 BusinessRules.Controls 集合中只有一个名为 "CheckBox1" 的控件。假设上面的评论中没有提到其他问题(比如在调用之前关闭表单),那么这应该可以解决您的问题