表格上有6个复选框。
第一部分:
每个复选框(第一个除外)用于隐藏/取消隐藏列。
第二部分:
第一个复选框选中/取消选中其他复选框,选中后将取消隐藏A到E中的列,取消选中后会隐藏它们。
总结一下:
checkbox-1: check/uncheck other 5 checkboxes and unhide/hide columns A-E
checkbox-2: hide/unhide column A
checkbox-3: hide/unhide column B
checkbox-4: hide/unhide column C
checkbox-5: hide/unhide column D
checkbox-6: hide/unhide column E
单击复选框2-6时,我尝试使用以下代码隐藏/取消隐藏列。有效。但是我将如何做第二部分?
Sub CheckBox_Click()
Dim vis As Boolean, ac As String, col As String
ac = Application.Caller
With ActiveSheet
vis = (.Shapes(ac).ControlFormat.Value = 1)
Select Case ac
Case "checkbox-2": col = "A"
Case "checkbox-3": col = "B"
...
End Select
If col <> "" Then .Columns(col).Hidden = vis
End With
End Sub
答案 0 :(得分:0)
将方框2-6连接到CheckTheBoxes宏,将方框1连接到InvertTheBoxes宏。
InvertTheBoxes循环通过工作表形状。每个不是“方框1”的形状都将被选中/取消选中,然后由CheckTheBoxes宏跟随。如果工作表上有更多形状,则需要稍微更改代码。但这是未经修改的答案:
Option Explicit
'checkbox-1: check/uncheck other 5 checkboxes and unhide/hide columns A-E
'checkbox-2: hide/unhide column A
'checkbox-3: hide/unhide column B
'checkbox-4: hide/unhide column C
'checkbox-5: hide/unhide column D
'checkbox-6: hide/unhide column E
Dim Vis As Boolean, Col$, Shp As Shape
Sub CheckTheBoxes(Optional ByVal AC$)
' If a checkbox runs this code, it will use Application.Caller,
' since the AC string would be emtpy.
' This way, you can run this macro from another macro (InvertTheBoxes),
' provided you return the shape name (which that macro does).
If AC = "" Then AC = Application.Caller
With ActiveSheet
Vis = (.Shapes(AC).ControlFormat.Value = 1)
Select Case AC
Case "checkbox-2": Col = "A"
Case "checkbox-3": Col = "B"
Case "checkbox-4": Col = "C"
Case "checkbox-5": Col = "D"
Case "checkbox-6": Col = "E"
End Select
If Col <> "" Then .Columns(Col).Hidden = Vis
End With
End Sub
Sub InvertTheBoxes()
Dim AC2$
AC2 = Application.Caller
With ActiveSheet
For Each Shp In .Shapes
If Shp.Name <> AC2 Then
' Change the checkbox status (from checked to unchecked and vice versa)
If Shp.ControlFormat.Value = 1 Then
Shp.ControlFormat.Value = -4146 ' Unchecked
Else
Shp.ControlFormat.Value = 1 ' Checked
End If
CheckTheBoxes Shp.Name ' Call the hide/show procedure
End If
Next Shp
End With
End Sub
如果要循环使用特定名称的形状,请尝试使用此InvertTheBoxes2宏:
Sub InvertTheBoxes2()
Dim AC2$
AC2 = Application.Caller
With ActiveSheet
For Each Shp In .Shapes
' Will only loop through shapes starting with "checkbox-"
If Left(Shp.Name, 9) = "checkbox-" And Shp.Name <> AC2 Then
' Change the checkbox status (from checked to unchecked and vice versa)
If Shp.ControlFormat.Value = 1 Then
Shp.ControlFormat.Value = -4146 ' Unchecked
Else
Shp.ControlFormat.Value = 1 ' Checked
End If
CheckTheBoxes Shp.Name ' Call the hide/show procedure
End If
Next Shp
End With
End Sub
只需确保您的其他复选框具有不同的名称,即“cbo-1”,“cbo-2”等。或者尝试更彻底地命名它们。