【问题标题】:Call a hiding macro with a checkbox使用复选框调用隐藏宏
【发布时间】:2022-11-01 23:25:51
【问题描述】:

我想制作一个复选框,调用一个宏来隐藏和取消隐藏 Excel 工作表上具有单元格中特定值的列,但它不起作用

我尝试了以下 VBA 脚本

Sub Hide_Forecasts()
Dim c As Range

    For Each c In Range("E12:CF12").Cells
        If c.Value = "Forecast" Then
            c.EntireColumn.Hidden = True
        End If
    Next c

End Sub
Sub Unhide_Forecasts()
    
Dim c As Range

    For Each c In Range("E12:CF12").Cells
        If c.Value = "Forecast" Then
            c.EntireColumn.Hidden = False
        End If
    Next c

End Sub
Sub CheckBox_For()
If CheckBox1.Value = True Then
    Call Hide_Forecasts
Else
    Call Unhide_Forecasts
End If
End Sub

请帮帮我

【问题讨论】:

  • 没有工作是什么意思?您是否收到错误,如果是,那是哪一行以及错误消息是什么?
  • Call 与 Application.Run() 可能需要研究...您需要指定这些是否都在同一个模块中,等等,就像 Warcupine 所说,详细说明您的问题。

标签: excel vba


【解决方案1】:

您还没有说您使用的是哪种类型的复选框 - 表单控件或 ActiveX 控件。

对于 ActiveX 控件,右键单击该控件并选择查看代码.
使用位于工作表后面的代码(CheckBox1 将以您的复选框命名)。

Private Sub CheckBox1_Click()
    Dim Cell As Range
    For Each Cell In Me.Range("E12:CF12")
        If Cell.Value = "Forecast" Then
            'Checkbox returns TRUE/FALSE - Hidden takes TRUE/FALSE so just connect the two up.
            Cell.EntireColumn.Hidden = Me.CheckBox1.Value
        End If
    Next Cell
End Sub

对于表单控件,右键单击该控件并选择分配宏.
将此代码放在普通模块中。
Sheet1 是工作表的代号(该名称不在项目资源管理器中的括号中)。

'Form Control can have three values:
' 1     = Checked
' -4146 = Unchecked
' 2     = Mixed - ignoring that this value may occur.
Public Sub Checkbox_For()

    Dim ChkValue As Boolean
    'Is value different from -4146?  Returns TRUE = Checked or Mixed / FALSE = Unchecked
    ChkValue = Sheet1.Shapes("Check Box 1").OLEFormat.Object.Value <> -4146

    Dim Cell As Range
    For Each Cell In Sheet1.Range("E12:CF12")
        If Cell.Value = "Forecast" Then
            Cell.EntireColumn.Hidden = ChkValue
        End If
    Next Cell
    
End Sub

【讨论】:

    猜你喜欢
    • 2013-09-25
    • 2016-05-03
    • 2013-03-23
    • 2013-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    相关资源
    最近更新 更多