VBA - 从单元格地址引用CheckBox

时间:2017-01-27 14:34:05

标签: excel vba excel-vba checkbox

我循环几行,我需要知道每行中的CheckBox是否“已检查”,但我不知道CheckBox的名称。以下代码只是为了说明问题:

Sub Checkboxes()

Dim ws As Worksheet
Set ws = Sheets("Input Data")
Dim Switch As Boolean

For i = 4 To 8
    Switch = ws.Cells(i, 11).CheckboxValue
    MsgBox Switch
Next i


End Sub

要创建复选框,我执行了以下操作:

  1. 创建一个CheckBox
  2. 将其放入单元格
  3. 在同一列中复制以下内容
  4. 我认为代码应与以下内容完全相反:

    CheckBox1.LinkedCell
    

2 个答案:

答案 0 :(得分:3)

这是一个很好的解决方法。代码将所有CheckBox链接到它们所在的单元格并给它们布尔值(TRUE / FALSE)。为了视觉外观,我使用过" Number Formating"这使得文本" TRUE / FALSE"无形。您需要做的就是使用Worksheet(CheckBoxes所在的位置)作为输入调用该函数。这个想法来自Aeneas

Public Function Link_Checkboxes_To_Cells(ws As Worksheet)

'This function is linking the checkboxes to the cells that they are in, so that the value of the cell becomes TRUE/FALSE when using the checkbox within.
'Meanwhile, I have manually made the text invisible in the cells with checkboxes, using the following method:
' https://support.office.com/en-us/article/Hide-or-display-cell-values-c94b3493-7762-4a53-8461-fb5cd9f05c33#bm1
' Number Type ---> Custom --> Then type ";;;" (without the quotes) and OK

Dim chk As CheckBox

For Each chk In ws.Checkboxes
   With chk
      .LinkedCell = _
         .TopLeftCell.Offset(0, 0).Address
   End With
Next chk

End Function

答案 1 :(得分:1)

...试

Sub Checkboxes()

    Dim ws As Worksheet
    Set ws = Sheets("Input Data")
    Dim Switch As Boolean

    For Each cb In ws.Checkboxes
        If cb.Value = 1 Then
            Switch = True
        Else
            Switch = False
        End If

        MsgBox cb.Name & " Value= " & Switch

    Next cb

End Sub