#头条创作挑战赛#
如何用VBA代码自定义表格配色?
1、窗体制作简单的颜色选择器
颜色选择器
2、模块中定义公共变量,则可以在窗体、工作表、模块之间相互引用
'在模块中设置公共变量,则窗体、工作表、模块之间可以相互调用
Public 颜色一 '标题栏背景色
Public 颜色二 '报表隔行背景色
Public 颜色三 '标题栏字体颜色
3、窗体事件:点击点选按钮选择不同的配色方案
代码
'蓝色系
Private Sub OptionButton1_Click()
颜色一 = RGB(82, 129, 185)
颜色二 = RGB(189, 215, 238)
颜色三 = RGB(255, 255, 255)
End Sub
'橙色系
Private Sub OptionButton2_Click()
颜色一 = Me.Label4.BackColor
颜色二 = Me.Label5.BackColor
颜色三 = Me.Label6.BackColor
End Sub
'绿色系
Private Sub OptionButton3_Click()
颜色一 = RGB(84, 130, 53)
颜色二 = RGB(226, 239, 218)
颜色三 = RGB(255, 255, 255)
End Sub
'黑白系
Private Sub OptionButton4_Click()
颜色一 = Me.Label10.BackColor
颜色二 = Me.Label11.BackColor
颜色三 = Me.Label12.BackColor
End Sub
'报表默认蓝色系
Private Sub UserForm_Initialize()
Me.OptionButton1.Value = True
End Sub
4、在过程中引用公共变量
代码
'//// 设置报表样式 ////
'表头
With Cells(h - 2, 1)
.Value = "供货商报表"
.Resize(1, 4).Merge '合并四列
.Font.Color = 颜色一 '字体颜色
.Font.Name = "新宋体" '字体
.Font.Size = 20 '字号
.Font.Bold = True '字体加粗
.RowHeight = 40 '行高
.HorizontalAlignment = xlCenter '居中
End With
'报表行高、列宽
Cells(h + 1, 1).Resize(dic.Count, 1).RowHeight = 18
Columns(1).ColumnWidth = 4.5
Columns(2).ColumnWidth = 40
Columns(3).ColumnWidth = 15
Columns(4).ColumnWidth = 10
'报表标题栏
With Cells(h, 1).Resize(1, 4)
.HorizontalAlignment = xlCenter '居中
.Font.Color = 颜色三 '字体颜色
.Font.Bold = True '字体加粗
.Font.Size = 12 '字号
.Interior.Color = 颜色一 '底色
.RowHeight = 23 '行高
.Borders.Color = 颜色二 '边框颜色
End With
'序号列
With Cells(h + 1, 1).Resize(dic.Count, 1)
.HorizontalAlignment = xlCenter '居中
End With
'数据区隔行填充颜色
Dim n As Integer
For n = 1 To dic.Count
n = n + 1
With Range("A" & n + h & ":" & "D" & n + h)
.Interior.Color = 颜色二 '背景颜色
.Borders(xlEdgeBottom).Color = 颜色二 '下边框颜色
.Borders(xlEdgeTop).Color = 颜色二 '上边框颜色
End With
Next n
'设置金额列格式
With Range(Cells(h + 1, 3), Cells(h + 1 + dic.Count, 3))
.NumberFormat = "#,##0.00;-#,##0.00"
End With
'设置“合计金额”四个字
With Cells(h + 2 + dic.Count, 2)
.Value = "合计金额"
.Font.Bold = True '字体加粗
.HorizontalAlignment = xlRight '字体居右
End With
'设置总金额格式
With Cells(h + 2 + dic.Count, 3)
.Font.Color = 颜色一 '字体颜色
.Font.Name = "Arial Black" '字体名称
.Font.Size = 13 '字号
.Font.Bold = True '字体加粗
.NumberFormat = "¥#,##0.00;-#,##0.00"
End With