如何在VBA中将字符串变量设置为颜色?

时间:2019-06-13 19:02:28

标签: excel vba string variables

我有一个输入框,要求输入一种颜色,例如“红色”或“绿色”,但是我想让一个子例程将单元格选择的背景设置为该颜色,而不仅仅是单词“ red”或“ “绿色”粘贴。这是我的代码:

Sub backgroundcolor()
Dim color As String
color = InputBox("Enter color")
Range("A1:B5").Interior.ColorIndex = color
End Sub

如何使用字符串(颜色名称)并将单元格范围设置为该颜色?

1 个答案:

答案 0 :(得分:0)

尝试一下

Sub backgroundcolor()
    Dim color As String
    color = InputBox("Enter color")
    If color = "" Then Exit Sub
    sColorsNameArr = Array("Black","White","Red","BrightGreen","Blue","Yellow","Pink","Turquoise","DarkRed","Green","DarkBlue","DarkYellow","Violet","Teal","Gray25","Gray50","PowderBlue","Plum","Cream","LightTurquoise","DarkPurple","Salmon","NavyBlue","LightLavender","DarkBlue2","Pink2","Yellow2","Turquoise2","Violet2","DarkRed2","Teal2","Blue2","SkyBlue","LightTurquoise2","LightGreen","LightYellow","PaleBlue","Rose","Lavender","Tan","LightBlue","Aqua","Lime","Gold","LightOrange","Orange","BlueGray","Gray40","DarkTeal","SeaGreen","DarkGreen","OliveGreen","Brown","Plum2","Indigo","Gray80") ' all 56 colors
    pos = Application.Match(color, sColorsNameArr, False)

    If Not IsError(pos) Then
       Range("A1:B5").Interior.ColorIndex = pos
    Else
       MsgBox color & " not found!"
    End If

End Sub