Search code examples
c#exceloffice-interop

Color non-consecutive cells in an Excel sheet


This is what happens:

enter image description here

xlValues is set as an Excel.Range object.

I have tried the following as well, all giving me the same error:

//xlValueRange = xlSheet...
.get_Range("A1:A5,A15:A25,A50:A65");
.UsedRange.Range["A1:A5,A15:A25,A50:A65"];
.Range["A1:A5,A15:A25,A50:A65"];

xlApp.ActiveWorkbook.ActiveSheet.Range["A1:A5,A15:A25,A50:A65"];
//I have also tried these alternatives with ".Select()" after the brackets and 
//", Type.Missing" inside the brackets

//This works though...
xlSheet.Range["A1:A5"];

I'm trying to recolor specific cells in an excel sheet, I have found a solution by using two loops but it's simply too slow. Running through a column of 30 000 cells takes minutes.

I have never done anything like this before and I used this tutorial to get me started.

This solution uses a bool array with cells to be colored set to true.(recolored)

//using Excel = Microsoft.Office.Interop.Excel;

xlApp = new Excel.Application();
xlApp.Visible = true;
xlBook = xlApp.Workbooks.Add(Type.Missing);
xlSheet = (Excel.Worksheet)xlBook.Sheets[1];

for (int i = 1; i < columns + 1; i++)
{
    for (int j = 1; j < rows + 1; j++)
    {
        if (recolored[j, i])
            xlSheet.Cells[j+1, i+1].Interior.Color = Excel.XlRgbColor.rgbRed;
        }
    }
}

What I would like to do is something like this:

Excel.XlRgbColor[,] color;
//Loop to fill color with Excel.XlRgbColor.rgbRed at desired cells.

var startCell = (Excel.Range)xlSheet.Cells[1, 1];
var endCell = (Excel.Range)xlSheet.Cells[rows, columns];
var xlRange = xlSheet.Range[startCell, endCell];

xlRange.Interior.Color = color;

This one gives me an error on the final line though;

Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))


My first guess would be to make an Excel.Range object that covers the cells I want to have red and use that object in place of xlRange, something like this:

RangeObject.Interior.Color = Excel.XlRgbColor.rgbRed;

I don't know if it's possible to make an Excel.Range object with gaps like that though, I could use some help on this one.


Solution

  • I had the same problem and it turned out that it was a bad list separator - in my case instead of comma there should be a semicolon.

    So instead of

    .Range["A1:A5,A15:A25,A50:A65"];
    

    try:

    private string listSep = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator;
    
    .Range["A1:A5" + listSep + "A15:A25" + listSep + "A50:A65"];