我正在使用Ms和一个带有10个复选框的表单和一个按钮。用户可以从1到10个复选框进行检查。每个复选框代表一个单词。我需要一个代码循环到1到10的所有复选框,并给我一个字符串,以便我可以将它解析为一个模块。
Private Sub cmdOK_Click()
Dim str1, str2, str3, str4, str5 As String
Dim strString As String
If chB1 = True Then
str1 = "111 - "
End If
If chB2 = True Then
str2 = "222 - "
End If
If chB3 = True Then
str3 = "333 - "
End If
If chB4 = True Then
str4 = "444 - "
End If
If chB5 = True Then
str5 = "555 - "
End If
strString = str1 & str2 & str3 & str4 & str5 & Date
Debug.Print strString
End Sub
我现在有这个。我可以用另一种方式吗? 有什么帮助吗?
提前谢谢。
答案 0 :(得分:4)
让每个CheckBox
控件在某个地方都有相关的字符串 - 可以是它的Caption
,也可以是它的Tag
,无论如何 - 你需要一种从复选框本身获取该字符串的方法,如果你想避免硬编码。
然后你可以迭代你的复选框,并使用一个动态数组调整大小到复选框的数量,你可以在每个数组索引中存储相关的字符串。
Dim items(), itemCount As Long
Dim ctrl As MSForms.Control, chkBox As MSForms.CheckBox
For Each ctrl In Me.Controls 'iterate all form controls
If TypeOf ctrl Is MSForms.CheckBox Then 'only care for checkboxes
Set chkBox = ctrl ' type cast to the MSForms.CheckBox interface
If chkBox.Value Then 'only care for checked checkboxes
itemCount = itemCount + 1
ReDim Preserve items(1 To itemCount)
items(itemCount) = chkBox.Tag 'or whatever you've mapped the strings to
End If
End If
Next
然后,您可以使用VBA.Strings.Join
函数将数组元素与要使用的任何分隔符连接起来:
Debug.Print Join(items, " - ")