excelvbacolorstextbox

Get color code to Excel Textbox from cell reference in VBA


I have the following VBA code in Excel which works fine

Sub Change_Color()

Color_TextBox4 = RGB(255, 255, 0)

Sheet03.Shapes("TextBox4").Select 
   With Selection.ShapeRange.Fill 
        .ForeColor.RGB = Color_TextBox4
    End With 
End Sub

However, I want that "Color_TextBox4" should source the color code from a cell in my Workbook as per below

Color_TextBox4 = Sheet03.Range("H1").Value`
Note: The text in cell H1 in Sheet03 = RGB(255, 255, 0)

The code then looks like

Sub Change_Color()

Color_TextBox4 = Sheet03.Range("H1").Value

Sheet03.Shapes("TextBox4").Select
    With Selection.ShapeRange.Fill
        .ForeColor.RGB = Color_TextBox4
    End With
End Sub

But when I run the code I get an error message

"Run-time error '13':
Type mismatch"

Do I need to declare/set "Color_TextBox4" in any specific way to make it work? Or what other changes do I need to do?


Solution

  • Sub Change_Color()
    
        Dim s As String, a
        s = Sheet03.Range("H1").Value
        s = Replace(Replace(s, ")", ""), "RGB(", "")
        a = Split(s, ",")
        
        With Sheet03.Shapes("TextBox4")
            .Fill.ForeColor.RGB = RGB(a(0), a(1), a(2))
        End With
        
    End Sub