数百个复选框从True / False更改为Yes / No

时间:2015-10-27 20:23:39

标签: excel vba excel-vba checkbox

我有一个不断更新的电子表格,以跟踪对患者的访问。我有2列,我使用下面的VBA代码输入多个复选框,其中分配给它们所在的单元格。但是,我想添加一些东西,当我点击它们时,复选框的值为Yes或No。电子表格中有600多个,所以我需要一些能够同时覆盖所有这些内容而不必分别更改每个内容的内容。我会张贴电子表格的图片,但我还不能,因为我是一个新用户并且没有声誉点。有人可以帮忙吗?

Sub AddCheckBoxes()

Dim cb As CheckBox
Dim myRange As Range, cel As Range
Dim wks As Worksheet

Set wks = Sheets("Sheet1")

Set myRange = wks.Range("K2:K300, L2:L300")

For Each cel In myRange

Set cb = wks.CheckBoxes.Add(cel.Left, cel.Top, 30, 6)


With cb

    .Caption = ""
    .LinkedCell = cel.Address

End With

Next

End Sub

End Sub

1 个答案:

答案 0 :(得分:2)

当代码创建复选框时,您可以添加.OnAction ="MacroName"

 With cb
        .LinkedCell = cel.Address
        .Caption = ""
        .OnAction = "YesNoChkBox"    'will call the macro when the checkbox is clicked.
    End With

这样做会在单击复选框时为其指定一个宏。然后,宏将计算出单击复选框的范围,如果为真或现在,将显示“是”或“否”。

 Sub MakeCkBx()

    Dim cb As CheckBox
    Dim myRange As Range, cel As Range
    Dim wks As Worksheet

    Set wks = Sheets("Sheet1")

    Set myRange = wks.Range("K2:K21, L2:L21")

    For Each cel In myRange

        Set cb = wks.CheckBoxes.Add(cel.Left, cel.Top, 30, 6)

        With cb
            .LinkedCell = cel.Address
            .Caption = ""
            .OnAction = "YesNoChkBox"    'will call the macro when the checkbox is clicked.
        End With
        cel.HorizontalAlignment = xlRight
    Next

End Sub
Sub YesNoChkBox()
    Dim r As Range, x, CkBx As CheckBox
    Set CkBx = ActiveSheet.CheckBoxes(Application.Caller)
    Set r = Range(CkBx.LinkedCell)

    If CkBx = 1 Then
        r = "yes"
    Else
        r = "No"
    End If
End Sub

运行MakeCkBx宏,然后单击复选框以获取结果。

我有application.caller位于here

的简单示例