标签:VBA,自定义函数
一个VBA自定义函数,生成随机颜色,可以专门排除不想要的颜色。一段过程代码,生成颜色索引及对应颜色的参考表,用以在自定义函数中指定你不需要的颜色提供参考。
'设置公共变量来记住值
Public pubPrevColor As Integer
'用途——该函数可以选择随机的颜色,也可以排除你不喜欢的颜色
Function intRndColor()
Dim Again As Label
Again:
intRndColor = Int((50 * Rnd) + 1) '随机生成
Select Case intRndColor
Case Is = 1, 3, 21, 35, 36 '你不想要的颜色
GoTo Again
Case Is = pubPrevColor
GoTo Again
End Select
pubPrevColor = intRndColor '将当前颜色赋给之前的颜色
End Function
'用于查看颜色,为随机颜色生成器选择不需要的颜色
Sub ViewColors()
Dim x As Integer
Sheets.Add
Cells(1, 1).Value = "颜色索引#"
Cells(1, 2).Value = "颜色示例"
For x = 2 To 58
Cells(x, 1).Value = x - 2
Cells(x, 2).Select
With Selection.Interior
.ColorIndex = x - 2
.Pattern = xlSolid
End With
Next x
Cells.Select
Cells.EntireColumn.AutoFit
With Selection
.HorizontalAlignment = xlCenter
End With
Cells(1, 1).Select
End Sub