【问题标题】:Multiple ActiveX buttons visible/hidden多个 ActiveX 按钮可见/隐藏
【发布时间】:2018-10-05 02:52:20
【问题描述】:

我在 excel 2013 中有一个工作表,上面有 25 个 activex 按钮。根据每个按钮的单元格值,我希望它是可见的或隐藏的。在我的情况下,单元格 U6 的值使我的 commandbutton1 可见,U7 将使 commandButton2 可见....只有我的 CommandButton1 正常工作。我尝试了不同的代码组合但没有成功。

    Private Sub CommandButton1_Click()
    End Sub
    Private Sub Worksheet_Change(ByVal Target As Range)
    'ActiveX button1
       If Range("U6") = 1 Then
        Sheets("Feuil1").CommandButton1.Visible = True
    Else
        Sheets("Feuil1").CommandButton1.Visible = False
      End If

   End Sub

【问题讨论】:

  • 如果Range("U6")=1,该代码确实看起来可以很好地使CommandButton1可见。对于其他不起作用的按钮,您有什么尝试,您如何定义“不起作用”?你有错误吗?没有得到您预期的结果?还有什么?
  • 所以...您向我们展示了有效的代码,并询问为什么我们没有看到的代码无效?

标签: vba


【解决方案1】:
If Range("U6") = 1 Then

那不应该检查Target(即修改后的单元格)是否在U列中吗?

Sheets("Feuil1").CommandButton1.Visible = True

那条路通向pastaland,你不想去那里:提取一个方法。您需要查询 OLEObjects 集合以按名称获取 ActiveX 控件,而不是对按钮名称进行 25 次以上的硬编码。

Private Sub SetControlVisibility(ByVal controlName As String, ByVal isVisible As Boolean)
    Dim axControl As OLEObject
    On Error Resume Next 'next statement may throw error #9
        Set axControl = Me.OLEObjects(controlName)
        If axControl Is Nothing Then Exit Sub
    On Error GoTo 0 'restore error handling
    axControl.Object.Visible = isVisible
End Sub

现在您有了一个方法,可以根据其名称切换工作表上任何 ActiveX 控件的可见性。

所以在Worksheet_Change 处理程序中,您现在只需要计算出ActiveX 控件的名称,以及是否希望它可见:

Private Sub Worksheet_Change(ByVal Target As Range)
    'bail out if the modified cell isn't interesting, or if it's more than 1 cell:
    If Intersect(Target, Me.Range("U6:U31") Is Nothing  Or Target.Count <> 1 Then Exit Sub

    Dim buttonName As String
    buttonName = "CommandButton" & Target.Row - 5

    Dim isVisible As Boolean
    isVisible = Target.Value = 1

    SetControlVisibility buttonName, isVisible
End Sub

或者类似的东西。注意:在答案框中编写的代码未经测试且仅用于说明目的。复制意大利面需要您自担风险。

【讨论】:

    猜你喜欢
    • 2022-08-13
    • 1970-01-01
    • 2022-01-21
    • 2021-11-27
    • 1970-01-01
    • 2020-09-22
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多