具有多个用户表单的复选框/单元链接

时间:2015-10-19 14:37:29

标签: arrays excel vba excel-vba checkbox

我很难理解VBA编码方法(我只有R经验)。我试图使用VBA将userform复选框的值链接到工作表中的特定单元格。

Sub x()
    Dim Range As Range

    If userfrom.checkbox1.Value = True Then
        Range.Offset(0, 7).Value = 1
    Else
        Range.Offset(0, 7).Value = ""
    End If


    If userform.checkbox2.Value = True Then
        Range.Offset(0, 8).Value = 1
    Else
        Range.Offset(0, 8).Value = ""
    End If


    If userform.checkbox3.Value = True Then
        Range.Offset(0, 9).Value = 1
    Else
        Range.Offset(0, 9).Value = ""
    End If

    Unload userform

End Sub

我遇到了为数组分配复选框的方法,但我无法理解线程中的示例。理想情况下,我想象的是声明一个复选框数组以及一个单元格数组 - 并将每个数组中的每个元素链接在一起,即checkboxArray(1) - > cellArray(1); checkboxArray(2) - > cellArray(2);等

我的一位同事检查了我的代码并说它可以做得更好,即在一行中完成。

这可以实现吗?

1 个答案:

答案 0 :(得分:0)

您可以简单地将Checkbox的ControlSource设置为工作表中的预定义单元格,并完全取消代码。

但是,如果您需要它是动态的,基于您正在使用的工作表或范围,这是一个功能强大的高效解决方案,它不依赖于表单上的复选框数量,并且易于更新。

顺便说一句,我不知道实际上是否可以在一行中完成。所有整数计数都是从OP中的代码中获得的。

Sub x()

Dim c As Control

For Each c In Controls

    If TypeName(c) = "CheckBox" Then

        i = Replace(c.Name, "CheckBox", "")

        If c.Value = True Then SetRange i + 6, 1 Else: SetRange i + 6, ""

    End If

Next

End Sub

Sub SetRange(i As Integer, sVal As String)

Dim wks As Worksheet
Set wks = Sheets("Sheet1") 'change to your sheet

With wks

    .Range("A1").Offset(, i).Value = sVal 'change "A1" to desired range

End With

End Sub