VBA多个复选框用户表单到单个单元格



>我正在使用一个包含多个复选框的用户表单。我的目标是让所有复选框将其值(唯一的两个字母首字母缩略词)返回到单个单元格。我不确定如何做到这一点。在今天之前,我没有 VBA 经验。

您可以录制一个宏来获取 VBA 的其他相关代码,但这应该会有所帮助:

Range("A" & LastRow).Value = CheckBox1.Value & CheckBox2.Value & CheckBox3.Value 'etc.
  'Concatenate CheckBox values with "&" (the values will be True or False though)

每个复选框的链接单元格设置为不同的单元格 - 例如复选框1到单元格A1,复选框2到单元格A2,等等对于每个链接单元格,在其相邻单元格中使用 If 公式来测试链接单元格的内容并返回字符串或空白,例如,单元格 B1 中的 if(A1=True,"AA","),单元格 B2 中的 if(A2=True,"BB",") 等最后,在另一个单元格中连接"if"公式的结果:例如 B1&","&B2&","&B3,使用逗号作为分隔符

为此,您可以创建表单中所有复选框的集合。这是我的代码:

Private mcolCHK As Collection 'This creates a modular level collection, which will keep track of all of the checkboxes
Private Sub cmdOK_Click()
    Dim objA As Object, strResults As String, i As Integer
    i = 1
    For Each objA In mcolCHK
        strResults = strResults & i & Left(objA.Value, 1)
        i = 1 + i
    Next
    Unload frmTestForm 'rename this the name of your form
    MsgBox strResults
    'instead of using a message box, you can say "strResults = Sheets(sheet1).range("A1").value
    'This part may be customized as needed
End Sub
Private Sub UserForm_Initialize()
    Set mcolCHK = New Collection
    mcolCHK.Add chkAtt1  'you will have to add one of these for each checkbox (simply replace "chkAtt1" with the name of your first checkbox
    mcolCHK.Add chkAtt2   'and repeat for each checkbox
End Sub

复选框始终给出 True 或 False 的值。 使用此方法,您将获得复选框的编号(按照您如何将它们添加到 UserForm_Initialize) 子集合中的顺序)和结果的第一个字母(T 或 F)。当我运行这个时,我有两个复选框,并在表单运行时选中每个复选框。这给了我一个"1T2T"的结果。这可以根据需要进行更改。您真正需要的是这一切是如何工作的。只需确保更改所有名称以匹配您使用的变量的名称即可。

最新更新