Get CommandButton name/ID in a cell

天涯浪子 提交于 2020-04-30 14:26:57

问题


I have a spreadsheet with CommandButtons in cells. I would simply like to Get the name/ID of the commandbutton in a particular cell without a button being clicked. How could I go about it ? I have been using this code but its inefficient as I have to type every button ID one by one. I have about 60 buttons.

 Sub Worksheet_Calculate()

  If Cells(6, 3).Value = 0 Then

    Me.Buttons("Button 55").Enabled = False
    Me.Buttons("Button 55").Font.ColorIndex = 16
Else
    Me.Buttons("Button 55").Enabled = True
    Me.Buttons("Button 55").Font.ColorIndex = 1

    End If

    If Cells(7, 3).Value = 0 Then

    Me.Buttons("Button 61").Enabled = False
    Me.Buttons("Button 61").Font.ColorIndex = 16
Else
    Me.Buttons("Button 61").Enabled = True
    Me.Buttons("Button 61").Font.ColorIndex = 1

    End If

回答1:


One way would be to loop through all the buttons on the worksheet and check the TopLeftCell for a match to your cell. Might bog down for a lot of buttons but I think 60 would run fine. May run into problems if you have overlapping buttons but you can probably avoid that. This looks at all Shapes, it's possible to narrow it down some but I wasn't sure which type of button you're using.

'In a worksheet module change Me. to a worksheet as needed.
Function findShape(r As Range) As String
    Dim s As Shape

    findShape = "Not Found" 'if loop goes all the way around and doesn't find it.

    For Each s In Me.Shapes
        If s.TopLeftCell.Address = r.Address Then
            findShape = s.Name
            Exit For 'no need to keep going
        End If
    Next
End Function


来源:https://stackoverflow.com/questions/30600055/get-commandbutton-name-id-in-a-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!