Looping through multiple Command Buttons to change their properties based on cell values

泄露秘密 提交于 2019-12-02 09:54:35

问题


I have an interactive table filled with over 100 different command buttons, each of which assign values to variables then use a custom function to calculate their output. They reference a table on the second sheet to get the values they assign. Is there a way to, based on whether a cell contains content or not, change the color of each button? So far, here's what I have (non-functional, of course).

Sub Auto_Open()
Dim n As Integer
n = 2
Do Until n = 114
    If Sheet2.Cells(n, 4) = vbNullString Or Sheet2.Cells(n, 5) = vbNullString Or Sheet2.Cells(n, 8) = vbNullString Or Sheet2.Cells(n, 9) = vbNullString Or Sheet2.Cells(n, 10) = vbNullString Or Sheet2.Cells(n, 11) = vbNullString Then
        ActiveSheet.Shapes.Range(Array("CommandButton" & (n - 1))).Select
        Range.Array(Selection).BackColor = 500
    Else
        ActiveSheet.Shapes.Range(Array("CommandButton" & (n - 1))).Select
        Range.Array(Selection).BackColor = 300
    End If
n = n + 1
Loop

End Sub

EDIT: I can't explicitly state the color for each command button without having to write in over 100 different cases. I have 112 different command buttons; I'd have to write 112 seperate IF statements.


回答1:


Example for one command button:

Dim cb As CommandButton
Set cb = Sheet1.CommandButton1
With Sheet2.Range("A1")
    If .Value = "Red" Then
        cb.BackColor = RGB(255, 0, 0)
    ElseIf .Value = "Green" Then
        cb.BackColor = RGB(0, 255, 0)
    Else
        cb.BackColor = RGB(155, 155, 155) ' gray
    End If
End With

If you want to loop through many command buttons, you can do as follows. In this example, I look at cells A1:A5 on Sheet2, and set the colors of Sheet1's commandbuttons 1 through 5 accordingly.

Dim cb As CommandButton
Dim i As Long

For i = 1 To 5
Set cb = Sheet1.Shapes("CommandButton" & i).OLEFormat.Object.Object ' Ouch!
    With Sheet2.Range("A1").Cells(i, 1)
        If .Value = "Red" Then
            cb.BackColor = RGB(255, 0, 0)
        ElseIf .Value = "Green" Then
            cb.BackColor = RGB(0, 255, 0)
        Else
            cb.BackColor = RGB(155, 155, 155) ' gray
        End If
    End With
Next i

The .Object.Object trick I got from here.



来源:https://stackoverflow.com/questions/25266267/looping-through-multiple-command-buttons-to-change-their-properties-based-on-cel

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