我想为 14 个标签着色 - 标签 1、标签 2、标签 3、....、标签 14。但是下面的代码出现类型不匹配错误...为什么?
Option Explicit
Private Const BackGrayPastel = 12832724
Private Const BackBlueIce = 14085355
Private Const BackChampagneMedium = 15984043
Private Const BackSnowCone = 11587026
Private Const BackSnowGoose = 14346730
Private Const BackSnowWite = 15922930
Private Const BackSnowDrift = 15326954
Private Const BackPinkCameo = 15711180
Private Const BackPinkMillenial = 16440029
Private Const BackRoseQuartz = 16239305
Private Const BackPurleBlueLight = 9611473
Private Const BackPurpleMedium = 1598786559
Private Const BackSalmon = 3868888575#
Private Sub UserForm_Initialize()
Dim r As Integer
Dim colorList As Range
Sheets("ColorCells").Select
Set colorList = Range("A1:A14") '<<<< 14 colors in 14 cells
For r = 1 To 14
With UserForm1
.Controls("Label" & r).BackColor = Range("A1").Offset(r, 0).Value '<<<< There are 14 labels Label1, Label2, Label3,...Label14
End With
Next r
End Sub
答案1
可能的解决方案。
定义颜色集合。在表单初始化时填充它。例如:
' Define private collection for colors
Private Colors As New Collection
Private Sub UserForm_Initialize()
' Fill colors collection
Colors.Add 12832724, "BackGrayPastel"
Colors.Add 14085355, "BackBlueIce"
Colors.Add 15984043, "BackChampagneMedium"
Colors.Add 11587026, "BackSnowCone"
Colors.Add 14346730, "BackSnowGoose"
Colors.Add 15922930, "BackSnowWite"
Colors.Add 15326954, "BackSnowDrift"
Colors.Add 15711180, "BackPinkCameo"
Colors.Add 16440029, "BackPinkMillenial"
Colors.Add 16239305, "BackRoseQuartz"
Colors.Add 9611473, "BackPurleBlueLight"
Colors.Add 1598786559, "BackPurpleMedium"
Colors.Add 3868888575#, "BackSalmon"
Dim i As Integer, Color As Long
' Iterate colors collection, paint labels
For Each Color In Colors
i = i + 1
Me.Controls("Label" & i).BackColor = Color
Next
End Sub
如果必须从工作表中读取颜色名称/代码 - 请这样做而不是直接分配。
您可以使用以下方式在此表单的模块中通过名称引用颜色代码:
Colors("color_name")
' or
Colors!color_name