【问题标题】:Excel VBA to change the caption on an Excel command buttonExcel VBA 更改 Excel 命令按钮上的标题
【发布时间】:2016-06-22 20:41:45
【问题描述】:

我正在寻找 Excel VBA 来动态更改 Excel 命令按钮上的标题。默认标题应为“显示差异”,并应在应用过滤器时更改为全部显示。

这是我目前所拥有的。

Sub ShowDifference()
Dim cmdButton As CommandButton

'在这里休息

Set cmdButton = ActiveSheet.Shapes("cmdShowDif")


If cmdButton.Caption = "Show Difference" Then
    ActiveSheet.ListObjects("qryDifference").Range.AutoFilter Field:=4, _
    Criteria1:=Array("<>0.00"), Operator:=xlAnd
    cmdButton.Caption = "Show All"
Else
    ActiveSheet.ListObjects("qryDifference").Range.AutoFilter Field:=4
    cmdButton.Caption = "Show Difference"
End If

End Sub

它打破了潜艇的名称。为什么?

错误:

【问题讨论】:

  • 错误是什么?
  • 它破坏了 sub 的名称 - 您是否先编译了代码?标题和这个问题到底有什么关系?
  • 抱歉忘记改标题了。错误信息见附图。
  • 您使用的是表单控件还是 ActiveX 控件?顺便说一句,错误是因为没有 CommandButton 这样的东西(声明变量时)。
  • 我正在使用默认的 Excel 命令按钮,我在其他地方找到了代码并对其进行了修改。在应用过滤器以及删除过滤器时,我正在尝试更改按钮上的标题。

标签: excel vba


【解决方案1】:

这是工作代码:

Sub ShowDifference()

Dim cmdButton As Button

Set cmdButton = ActiveSheet.Buttons("cmdShowDif")

If cmdButton.Caption = "Show Difference" Then
    cmdButton.Caption = "Show All"
Else
    cmdButton.Caption = "Show Difference"
End If

End Sub

或者,您也可以使用以下代码:

Sub ShowDifference()

Dim cmdButton As Button

For Each cmdButton In ActiveSheet.Buttons
    If cmdButton.Name = "cmdShowDif" Then
        If cmdButton.Caption = "Show Difference" Then
            cmdButton.Caption = "Show All"
        Else
            cmdButton.Caption = "Show Difference"
        End If
    Else
        Debug.Print cmdButton.Name & " is not the one... moving to next button..."
    End If
Next cmdButton

End Sub

如果您有任何问题,请告诉我。

【讨论】:

    【解决方案2】:

    转到“开发人员”选项卡并单击“设计模式”。现在选择您的命令按钮。按钮的名称将出现在名称框中 - 位于编辑栏的左侧。改变这一行

    Set cmdButton = ActiveSheet.Shapes("cmdShowDif")
    

    到

    Set cmdButton = ActiveSheet.OLEObjects("cmdShowDif").Object
    

    但这使用正确的名称而不是cmdShowDif(或将名称框中的名称更改为cmdShowDif

    【讨论】:

    • 这仅适用于 ActiveX 控件。但在我看来,Karen 正在使用表单控件。
    • CommandButton 数据类型是 ActiveX,Shapes() 访问器在 Forms 中更常用。我想知道她从哪里复制了该代码以及他们到底在使用什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2012-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多