我的工作簿包含多个工作表,每个工作表都有多个复选框。所有工作表中的所有复选框都在第80行中具有链接的单元格。在名为“Info”的工作表中,我使用countif来计算所有工作表中行(80)中文本“TRUE”出现的总次数。总数在Info!B8。
每次Cell Info!b8更改时,我都需要调用一个宏。换句话说;每次单击一个复选框时,链接的单元格都会更改,单元格信息!b8会上升或下降,我需要一个宏来运行。
这是我正在使用的代码,但它没有做任何事情。我已经研究了这个,从我能说的它应该起作用了吗?
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$B$8" Then
Call CreateFinalWorksheet
End If
End Sub
答案 0 :(得分:1)
假设您的所有CheckBox都是Form Controls,稍微改变了CheckBox创建,您可以实现所需,而无需 LinkedCell 和 CountIfs 等。
示例:下面的 CreateCheckBoxes()将为Range(“D1:D5”)中的每个单元格创建一个复选框,使用前缀和单元格地址命名,指定Sub 单击时CheckBoxClicked 。
在Sub CheckBoxClicked()
中,它将遍历所有工作表(名为“Info”除外),如果名为ending D3 的复选框的值为1(勾选),则递增计数器。之后,如果达到阈值,则会调用Sub CreateFinalWorksheet()
。
Option Explicit
Private Const ChkBoxPrefix As String = "cbx_"
Private Const ThresholdToCreateFinalWorksheet As Long = 3
Sub CreateChkBoxes()
Dim myCBX As CheckBox, c As Range
For Each c In Range("D1:D5") 'rngCB
With c
Set myCBX = ActiveSheet.CheckBoxes.Add(Top:=.Top, Width:=.Width, Height:=.Height, Left:=.Left)
End With
With myCBX
.Name = ChkBoxPrefix & c.Address(0, 0)
.Caption = "Check Box " & c.Address(0, 0) 'strCap
.OnAction = "CheckBoxClicked" ' "CheckBox_Click"
End With
Next c
End Sub
Sub CheckBoxClicked() ' CheckBox_Click()
Dim oWS As Worksheet, lChecked As Long
On Error Resume Next ' Just in case the named CheckBox does not exist
lChecked = 0
For Each oWS In ThisWorkbook.Worksheets
If oWS.Name <> "Info" Then
' If you need to keep track of more than 1 checkbox in each worksheet, go through them
' If you need all of them to be checked before CreateFinalWorksheet, exit when a checkbox.value = 0
With oWS.CheckBoxes(ChkBoxPrefix & "D3") ' <-- Change to what you need to keep track of
lChecked = lChecked + IIf(.Value = 1, 1, 0)
End With
End If
Next
On Error GoTo 0
If lChecked >= ThresholdToCreateFinalWorksheet Then CreateFinalWorksheet
End Sub
Private Sub CreateFinalWorksheet()
Debug.Print "CreateFinalWorksheet()"
End Sub
或者您将事件Sub Worksheet_Calculate()
放入 Info 模块,并检查 Info!B8 是否足够大以调用CreateFinalWorksheet。