VBA:在表单控件中触发事件

时间:2015-12-29 05:58:05

标签: excel vba excel-vba checkbox form-control

我正在Excel中使用复选框处理WBS。

我有以下内容:

  

[checkbox1] A级   --------- [checkBox2]第1项   --------- [checkBox3]第2项   [checkbox4] B级   --------- [checkBox5]第3项

当我取消选中checkbox2时,它会在项目1旁边的单元格中放置一个X. 如果我勾选checkbox2,它将删除X。

如果我取消选中checkbox1,它将取消选中checkbox2和checkbox3,但它不会在项目1和2旁边的单元格中放置一个X.它只是取消勾选两个复选框而不触发事件。如何将该事件链接到checkBox1?

如果无法在Form Control中触发那种事件,那么我的其他问题就是知道如何知道复选框所在的行和列 在ActiveX控件?

在表单控件中,我们可以使用sheets("sheet1").checkboxes(application.caller),但这在ActiveX控件中不起作用。

checkbox2或checkbox3的代码:

Sub CheckBoxLine()
Dim ws As Worksheet
Dim chk As CheckBox
Dim lColD, myCol As Long
Dim lColChk As Long
Dim lRow As Long
Dim rngD As Range
lColD = 1 'number of columns to the right
Set ws = ActiveSheet
Set chk = ws.CheckBoxes(Application.Caller)
lRow = chk.TopLeftCell.Row
lColChk = chk.TopLeftCell.Column
Set rngD = ws.Cells(lRow, lColChk + lColD)

Select Case chk.Value
Case 1   'box is checked
  rngD.Value = "X"
Case Else   'box is not checked
  rngD.Value = "X"

End Select

End Sub

checkbox1的代码:

Select Case chk.Value
Case 1   'box is checked
  For Each cb In ws.CheckBoxes
    If cb.Name = "Check box 2" Then
        cb.Value = 1
    End If

    If cb.Name = "Check box 3" Then
        cb.Value = 1
    End If
  Next cb

Case Else   'box is not checked
  For Each cb In ws.CheckBoxes
    If cb.Name = "Check box 2" Then
        cb.Value = 0
    End If

    If cb.Name = "Check box 3" Then
        cb.Value = 0
    End If
  Next cb
End Select

1 个答案:

答案 0 :(得分:0)

澄清后答案发生了变化。

我认为表单控件没有事件。 AFAIK获取ActiveX控件所在的单元格有点复杂。我在我的一个工作簿中完成了它,但它需要一些额外的类模块中的代码,我不记得如何实现它。

由于您使用表单控件复选框,我认为使用以下代码会更容易,而不是使用新创建的ActiveX复选框中的事件。我希望它可以按你的需要工作。

Option Explicit
Dim ws As Worksheet

Sub CheckBoxLine(Optional strChkName As String)
    Dim chk As CheckBox
    Dim lColD, myCol As Long
    Dim lColChk As Long
    Dim lRow As Long
    Dim rngD As Range

    lColD = 1 'number of columns to the right
    If ws Is Nothing Then Set ws = ActiveSheet
    If strChkName = vbNullString Then
        Set chk = ws.CheckBoxes(Application.Caller)
    Else
        Set chk = ws.CheckBoxes(strChkName)
    End If
    lRow = chk.TopLeftCell.Row
    lColChk = chk.TopLeftCell.Column
    Set rngD = ws.Cells(lRow, lColChk + lColD)

    Select Case chk.Value
    Case 1   'box is checked
      rngD.Value = vbNullString
    Case Else   'box is not checked
      rngD.Value = "X"
    End Select

    Set chk = Nothing
    Set ws = Nothing
End Sub

Sub Code_for_Checkbox1()
    Set ws = ActiveSheet
    ws.CheckBoxes("Check Box 2").Value = ws.CheckBoxes(Application.Caller).Value
    ws.CheckBoxes("Check Box 3").Value = ws.CheckBoxes(Application.Caller).Value
    Call CheckBoxLine("Check Box 2")
    Call CheckBoxLine("Check Box 3")
End Sub