I have the following code:
Excel.Range chartRange;
chartRange = xlWorkSheet.get_Range("A3", "R3");
I want to fill this range of cells with a color. I have already tried with:
System.Drawing.Color = "yellow"
but it is throwing an exception that an object reference is required.
How can I fix my code to fill these cells with a color?
You are directly assigning the color to the worksheet variable which Excel interop cant understand.
So you need to convert those color values to OLE values by using colorTranslator.ToOle method or use Excel way of coloring it. Provided both the ways.
else
Here xlWorksheet is the object excel Worksheet object.
get_Range takes 2 variable one start cell and other is end cell.
so if you specify both the values same then only one cell is colored.
xlWorkSheet.cells[row, column] is used to specify a cell.
System.Drawing.ColorTranslator.ToOle(SystemDrawing.Color.Green) is used to define the color in OLE format.
Excel.XlRgbColor.rgbRed is a excel way of coloring the cells This method gives access to large number of colors which can be found here list of colors
The problem with your code shown above is that you can't assign the string value "Yellow" to the
System.Drawing.Color
type. Instead, the standard colors are exposed as read-only properties that you can access through theColor
structure. The full list is given in the documentation.Excel interop makes things a bit more complicated, because you need to convert those color values to OLE colors. You do this using the
ColorTranslator.ToOle
method.So, for example, you need to add the following line to your original code:
For more information, also consult this how-to article on MSDN.
Try this: