【问题标题】:How to do the same code for several checkboxes to set the checkbox Value?如何为多个复选框执行相同的代码来设置复选框值?
【发布时间】:2016-05-30 23:48:52
【问题描述】:

我的 Excel 用户表单中有几个复选框(总共 10 个),它们都应该具有相同的行为。这意味着,当我重新加载表单时,复选框的值应该会发生变化,具体取决于电子表格中实际选定行的值。

以下代码对一个复选框正常工作:

If Sheet1.Cells(iRow, Sheets("aux").Range("B21")) = "X" Then
    cbERW.Value = True
ElseIf Sheet1.Cells(iRow, Sheets("aux").Range("B21")) = "?" Then
    cbERW.Value = Null
Else
    cbERW.Value = False
End If

如何以最简单的方式为多个复选框执行此操作?但是对于每个复选框,引用的行和列都可能发生变化。例如,下一个看起来像这样(cbHSAW 而不是cbERW,列B22 而不是B21):

If Sheet1.Cells(iRow, Sheets("aux").Range("B22")) = "X" Then
    cbHSAW.Value = True
ElseIf Sheet1.Cells(iRow, Sheets("aux").Range("B22")) = "?" Then
    cbHSAW.Value = Null
Else
    cbHSAW.Value = False
End If

有人知道如何轻松做到这一点吗?

【问题讨论】:

    标签: vba excel checkbox


    【解决方案1】:

    您可以将测试语句包装在一个函数中并传递特定复选框的范围。然后设置返回结果可以作为复选框的值。以下内容需要针对您的表单和范围进行修改,但会提供所需的结果。

    'Function to test the value of the range
    Private Function SetCheckBox(ByVal rng As Range)
    If rng.Value = "X" Then
        SetCheckBox = True
    ElseIf rng.Value = "?" Then
        SetCheckBox = Null
    Else
        SetCheckBox = False
    End If
    End Function
    
    
    Private Sub UserForm_Initialize()
    'Set value for each checkbox by passing its range to the function
    CheckBox1.Value = SetCheckBox(Sheets("aux").Range("A1"))
    CheckBox2.Value = SetCheckBox(Sheets("aux").Range("A2"))
    CheckBox3.Value = SetCheckBox(Sheets("aux").Range("A3"))
    CheckBox4.Value = SetCheckBox(Sheets("aux").Range("A4"))
    End Sub
    

    【讨论】:

    • 不客气。如果此答案解决了您的问题,您会将其标记为答案吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-05
    相关资源
    最近更新 更多