Changing the Color of a Dynamic Form Button

DrRonald

New Member
Joined
May 18, 2011
Messages
6
I am new to VBA. I am trying to figure out a way to change the background color of a button that I am programmatically adding to a Userform. An example of the code I am using is a follows:

Code:
Dim rnge As Range
Dim ws As Worksheet
Dim cControl As Control
Dim c As Integer
Dim NName As String
c = 1
Set ws = Worksheets("Main")
For Each rnge In ws.Range("RngeName")
    Set cControl = Me.Controls.Add("Forms.CommandButton.1", True)
        With cControl
            .Width = 50
            .Height = 20
            .Top = 20 + c * 40
            .Left = 60
            .Caption = rnge
            .Name = "but" & rnge
            .ZOrder (0)
        End With

    NName = cControl.Name

        With     ActiveWorkbook.VBProject.VBComponents("UserForm").CodeModule
            X = .CountOfLines
            .InsertLines X + 1, "Sub " & NName & "_Click()"
            .InsertLines X + 2, "UserForm.Hide"
            .InsertLines X + 3, "End Sub"
        End With
    c = c + 1
Next rnge

End Sub
I have read that you can't change the background of these buttons, but I know for a fact that you can change the color. I can do this by adding a line after the first with such as ".BackColor = "... The problem I am having is changing the color outside the For statement. That is, I want to change the color at some point after initially creating the buttons.

Also, I can't get the code which I am adding to those buttons to work. The "UserForm.Hide" is just a test, but it doesn't work. The code is added correctly, but the button still doesn't do anything. Thanks very much.
 

Excel Facts

Links? Where??
If Excel says you have links but you can't find them, go to Formulas, Name Manager. Look for old links to dead workbooks & delete.

Forum statistics

Threads
1,223,908
Messages
6,175,306
Members
452,633
Latest member
DougMo

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top