将所有复选框转换为一个字符串

将所有复选框转换为一个字符串

问题描述:

我正在使用Ms Access,并且有一个窗体上有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

如果'CheckBox1'被选中,它的价值将是TRUE;。如果它的值是'True',你想要将它的'Caption'连接到你的结果字符串中。继续使用“CheckBox2”。你坚持哪部分? –

+0

添加代码。我可以用循环来做到吗? – YvetteLee

让每个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, " - ")