Excel VBA 根据单元格值隐藏按钮

Excel VBA hiding a button based on a cell value

我有一个 500 行的电子表格,每行的 M 列中都有一个表单“属性”按钮。

该按钮效果很好,单击时会执行宏,显示该行的信息。

我将按钮复制到 500 行电子表格的同一列,因此每一行都有一个按钮。但我真正想要的是,如果该行 A 列上的单元格为空,则隐藏该按钮。有办法吗?

作为参考,我在单击时使用的按钮下方添加了代码。目前 M 列中的每个按钮都引用了下面的宏。

Sub Button17_Click()

    Dim x As Variant
    Dim y As Variant
    ' Find Row and Column of clicked button
    Dim B As Object, csNew As Integer, rsNew As Integer
    Set B = ActiveSheet.Buttons(Application.Caller)
    With B.TopLeftCell
        csNew = .Column
        rsNew = .Row
    End With
    'Find out if the row item is "SWGR/MCC/XFMR"
    x = Sheets("Worksheet").Cells(rsNew, csNew + 17).value
    y = Sheets("Worksheet").Cells(rsNew, csNew - 11).value
    If x = "SWGR" And y = "XFMR" Then
        UserForm1.Show
    ElseIf x = "MCC" And y = "XFMR" Then
        UserForm2.Show
    ElseIf x = "MCC" Then
        UserForm3.Show
    ElseIf x = "SWGR" Then
        UserForm4.Show
    End If
Debug.Print "Button initialized"

End Sub

需要某些东西来触发 hide/unhide 按钮的代码,因此请尝试 sheet 代码模块中的 worksheet_change 事件处理程序:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim rng As Range, c As Range, b As Object
    'only interested in ColA changes
    Set rng = Application.Intersect(Target, Me.Columns("A"))
    If Not rng Is Nothing Then
        'check each changed cell
        For Each c In rng.Cells
            Set b = buttonFromCell(c)
            If Not b Is Nothing Then
                b.Visible = Len(c.Value) > 0 'visible only if has value
            End If
        Next c
    End If
    
End Sub

'Find a button on the same row as c
Function buttonFromCell(c As Range)
    Dim b As Object
    For Each b In Me.Buttons
        If b.TopLeftCell.Row = c.Row Then
            Set buttonFromCell = b
            Exit Function
        End If
    Next
    Set buttonFromCell = Nothing '<< no button found
End Function