Excel - 填充不同颜色的单元格

时间:2016-07-07 09:33:44

标签: excel vba excel-vba

我需要在这张照片中填充不同颜色的单元格(3行垂直合并,并使用3个矩形形状在此图片中手动绘制颜色):

Fill cell with different colors

我能找到填充单元格的一部分的唯一方法是使用条件格式(通过将样式设置为数据栏并填充为实体)但它仅支持一种颜色。 无论是否有VBA都可以吗?

1 个答案:

答案 0 :(得分:0)

有可能。

我找到了两种方法。

1-使用黑色方形字符(字符代码2588-vba:ActiveSheet.Cells(1,1)= ChrW(& H2588))并根据百分比对它们着色。此字符填充单元格高度,并且它们之间没有间距,这样可以完全填充单元格(当然,您应该考虑单元格中的左缩进)。这里只发布一个单元格中不能使用大量字符的问题;我使用其中的30个并根据30来缩放字符数(即50%红色表示15个红色字符-2588)。

2-它与@Doktor Oswaldo建议的相同:使用单元格的位置和大小(以像素为单位)在单元格中插入绘图。这种方法有一个很大的优点:你可以准确地显示比率。此外,您还可以使用模式填充数据系列。但是,如果你有很多情节,你将牺牲Excel的表现。对于绘图设置,我使用以下VBA代码:

    'Define var's
Dim src As Range, targetCell As Range
Dim chacha As ChartObject

'Set var's
Set src = Worksheets("Sheet1").Range("B1:B3")
Set targetCell = Worksheets("Sheet1").Range("C2")

'Create plot at the target cell
Set chacha = Sheets("Sheet1").ChartObjects.Add(targetCell.Left, targetCell.Top, targetCell.Width, targetCell.Height)

'Change plot settings to fill the cell
With chacha.Chart
    .ChartType = xlBarStacked
    .SetSourceData Source:=src, PlotBy:=xlRows
    .Axes(xlValue).MinimumScale = 0
    .Axes(xlValue).MaximumScale = 100
    .Axes(xlCategory).Delete
    .Axes(xlValue).Delete
    .Legend.Delete
    .PlotArea.Top = -50
    .PlotArea.Left = -50
    .PlotArea.Width = targetCell.Width
    .PlotArea.Height = targetCell.Height
    .ChartGroups(1).GapWidth = 0
End With

chacha.Chart.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
chacha.Chart.SeriesCollection(2).Format.Fill.ForeColor.RGB = RGB(0, 0, 255)
chacha.Chart.SeriesCollection(3).Format.Fill.ForeColor.RGB = RGB(255, 255, 0)

在代码中我手动修改了系列颜色,也可以自动化。以下是两种方法的屏幕截图。 Cell" C1"填充了块字符和" C2"是一张图表。

FillCellPlot

注意:您可能会在第34行.PlotArea.Top"中遇到错误。要解决此问题,请查看:Error setting PlotArea.Width in Excel, VBA (Excel 2010)