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:
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.
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
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.