HOW TO: How do I set a cell's color?

Reference: Q0021

Article last modified on 3-Feb-2006


The information in this article applies to:

  • XLL+ for Visual Studio .NET - 3, 4.1, 4.2, 4.3.1
  • XLL+ for Visual Studio 6 - 3, 4.1, 4.2, 4.3.1

How do I set a cell's color?

Question

How can I set the font color and background color of a specific cell from an XLL add-in function?

Answer

To set the foreground (text) color of the current selection, use the CXlMacros::FontProperties method, as follows:

#include <xlfuncs.h>
...			
    int foreColorIndex = 4; // green
    if (CXlMacros::FontProperties(0, 0, 0, -1, -1, -1, -1,
            foreColorIndex) != 0)
        CXllApp::XlMessageBox("Failed to set fore color", 1);

To set the background color of the cells currently selected, use the XLM4 function PATTERN to set the cells to have a solid pattern with the specified background color, thus:

    int backColorIndex = 3; // red
    static int xlcPatterns = (84 | 0x8000);
    if (CXllApp::Excel(xlcPatterns, 4, 
        &CXlOper(1.0),                      // pattern = solid
        &CXlOper(0.0),                      // fore color (ignored)
        &CXlOper((double)backColorIndex),   // specified cell color
        &CXlOper(TRUE)) != 0)
        CXllApp::XlMessageBox("Failed to set back color", 1);

The color indices above can be numbers between 1 and 56 corresponding to the 56 colors shown in the Cell Formattting dialogs. The function ShowCellColor() in the sample faq0021_colors.zip can be used to find the values of these color indices.

See Also