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

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

用不同的颜色填充单元格

我可以find填充单元格的唯一方法是使用条件格式(通过将样式设置为数据栏并填充为实体),但它只支持一种颜色。 这可能有或没有VBA?

有可能的。

我find了两种方法来做到这一点。

1-使用黑色正方形字符(字符代码2588 – vba:ActiveSheet.Cells(1,1)= ChrW(&H2588))并根据百分比对它们进行着色。 这个字符填满了单元格的高度,而且它们之间没有间距,这就允许完全填满单元格(当然,你应该考虑单元格中的左缩进)。 只有在这里问题,你不能在一个单元格中使用很多字符; 我使用了30个字符,并根据30来缩放字符数(即50%的红色表示15个红色的字符-2588)。

2-与@Doktor Oswaldobuild议的一样:使用单元格的位置和大小以像素为单位在单元格中插入一个绘图。 这种方法有一个很大的优点:可以精确地显示比率。 另外,你也可以用一个模式填充一个数据序列。 但是如果你有很多的情节,你会牺牲Excel的performance。 对于绘图设置,我使用以下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) 

在代码中我手动修改了系列颜色,也可以自动化。 以下是两种方法的截图。 单元格“C1”填充了块字符,“C2”是一个图表。

FillCellPlot

注意:您可能会在“.PlotArea.Top”行发生错误。 要解决此问题,请检查: 在Excel,VBA(Excel 2010)中设置PlotArea.Width时出错,