Setting Conditional Formatting in Excel 2007
Summary: Learn how to apply conditional formatting programmatically in Excel 2007.
Applies to: 2007 Microsoft Office System, Microsoft Office Excel 2007
Joel Krist, Akona Systems
To illustrate how to programmatically set conditional formatting in Excel 2007, this section walks through five steps:
To programmatically set conditional formatting in Excel 2007
Add a reference to the Excel 12.0 Object Library.
Import the Excel interop assembly namespace.
Create a new workbook and add a worksheet to it.
Implement the conditional formatting.
1. Add a Reference to the Excel 12.0 Object Library
First, add a reference to the Microsoft Excel 12.0 Object Library to the Visual Studio project. To do this, right-click on the project in the Visual Studio Solution Explorer and select the Add Reference… menu item. Select the COM tab in the Add Reference dialog box, then scroll down to the Microsoft Excel 12.0 Object Library component, select it, and then click OK to add the reference.
2. Import the Excel Interop Namespace
Next, import the Microsoft.Office.Interop.Excel namespace to allow access to the objects defined in the Microsoft Excel 12.0 Object Library without having to specify the full namespace path. Add the following line to the top of the source file.
To import the namespace for Visual Basic projects, right-click the project in the Visual Studio Solution Explorer and select the Properties menu item. On the project properties page select the References tab and then select the checkbox next to the Microsoft.Office.Interop.Excel entry in the list of imported namespaces.
3. Declare Variables
The following block of code declares variables that hold references to the Excel objects used by the conditional formatting code.
Dim excelApplication As ApplicationClass = Nothing Dim newWorkbook As Workbook = Nothing Dim targetSheet As Worksheet = Nothing Dim cfColorScale As ColorScale = Nothing Dim cfIconSet As IconSetCondition = Nothing
The following lines of code declare two variables that help to make the parameters passed to methods used in the conditional formatting code easier to read.
Use the paramWorkbookPath variable to specify the path and filename when you save the new Excel 2007 workbook. It is set to C:\Temp\Test.xlsx in the sample code, but you can change this as needed.
Use the paramMissing variable to call methods that accept optional parameters. Optional parameters are only optional when you use Microsoft Visual Basic. You must specify a value for optional parameters when you use Microsoft Visual C#. Using Type.Missing as the value for an optional parameter tells the method being called that the parameter is not being specified and that the method should use the parameter's default value.
4. Create a New Workbook
The following code creates an instance of Excel 2007 and creates a workbook with one worksheet in it named Conditional Formatting.
5. Implement the Conditional Formatting
The following block of code fills cells A1:A10 with sample data and then applies conditional formatting to the data using a two-color color scale. The Visual Basic version of the code uses the built-in RGB function to generate the color values for the minimum and maximum threshold values, whereas the C# version uses hard-coded values for these settings. The reason for this difference is because the RGB function does not exist for C# and the System.Drawing.Color class cannot be used directly to generate the color values in the correct format. The format issue has to do with the difference in the way that the Microsoft .NET Framework and COM represent RGB color values.
In the .NET Framework, colors are represented using the System.Drawing.Color class. The Color class stores a color's RGB component values as an integer in the AARRGGBB format. The two most significant bytes represent the color's alpha value, followed by the red, green, and blue color component values. You can obtain the ARGB value using the Color object's ToArgb() method, such as Color.Red.ToArgb(). However, COM handles colors differently than the .NET Framework does. In COM, colors are represented as an integer in the 00BBGGRR format. The alpha component is 0 and the blue component is in a more significant byte position than the red component. This differs from the .NET Framework.
Because the object model for Excel 2007 is COM-based, the ColorScaleCriterion.FormatColor.Color property expects a color value as an integer with the color components in the 00BBGGRR order. Trying to set the ColorScaleCriterion.FormatColor.Color property to a value returned from a Color object's ToArgb() method does not work because the bytes for the color's red and blue components are swapped. You could create a C# method that would be the equivalent of the Visual Basic RGB function, but for the purposes of this article, the code simply uses hard-coded values.
' Fill cells A1:A10 with sample data. targetSheet.Range("A1").Value = 1 targetSheet.Range("A2").Value = 2 targetSheet.Range("A1:A2").AutoFill(targetSheet.Range("A1:A10")) ' Create a two-color ColorScale object for the created sample data ' range. cfColorScale = _ targetSheet.Range("A1:A10").FormatConditions.AddColorScale(2) ' Set the minimum threshold to red and maximum threshold to blue cfColorScale.ColorScaleCriteria(1).FormatColor.Color = RGB(255, 0, 0) cfColorScale.ColorScaleCriteria(2).FormatColor.Color = RGB(0, 0, 255)
The following block of code fills cells C1:C10 with sample data and then uses the five-arrow icon set to apply conditional formatting to the data.
' Fill cells from C1:C10 with sample data. targetSheet.Range("C1").Value = 55 targetSheet.Range("C2").Value = 92 targetSheet.Range("C3").Value = 88 targetSheet.Range("C4").Value = 77 targetSheet.Range("C5").Value = 66 targetSheet.Range("C6").Value = 93 targetSheet.Range("C7").Value = 76 targetSheet.Range("C8").Value = 80 targetSheet.Range("C9").Value = 79 targetSheet.Range("C10").Value = 83 ' Create an icon set conditional format for the created sample data ' range. cfIconSet = targetSheet.Range("C1", _ "C10").FormatConditions.AddIconSetCondition() ' Change the icon set to a 5-arrow icon set. cfIconSet.IconSet = newWorkbook.IconSets(XlIconSet.xl5Arrows) ' The IconCriterion collection contains all the icon criteria. ' Each criteria can be modified by indexing into the collection. ' The following code sets the criteria for each of the arrows ' in the set. With cfIconSet.IconCriteria(2) .Type = XlConditionValueTypes.xlConditionValueNumber .Value = 60 .Operator = XlFormatConditionOperator.xlGreaterEqual End With With cfIconSet.IconCriteria(3) .Type = XlConditionValueTypes.xlConditionValueNumber .Value = 70 .Operator = XlFormatConditionOperator.xlGreaterEqual End With With cfIconSet.IconCriteria(4) .Type = XlConditionValueTypes.xlConditionValueNumber .Value = 80 .Operator = XlFormatConditionOperator.xlGreaterEqual End With With cfIconSet.IconCriteria(5) .Type = XlConditionValueTypes.xlConditionValueNumber .Value = 90 .Operator = XlFormatConditionOperator.xlGreaterEqual End With
Save the Workbook
Save the workbook and exit Excel 2007. The following C# code passes the XlSaveAsAccessMode.xlNoChange value as the seventh parameter to the Workbook.SaveAs method. This is done instead of using the paramMissing variable because the SaveAs method takes an XlSaveAsAccessMode enumerated type rather than an object type for this parameter. For the purposes of this article, the actual value from the XlSaveAsAccessMode enumeration that is passed to the SaveAs method is not important.
After the code saves the Excel 2007 workbook, it closes the workbook and the application objects and releases references to the underlying Excel 2007 COM objects. This allows Excel 2007 to unload from memory. For more information about how to release COM objects when using managed code, see Chapter 2: Basics of Office Interoperability (Part 2 of 3) from Microsoft .NET Development for Microsoft Office.
newWorkbook.SaveAs(paramWorkbookPath) ' Release the references to the Excel objects. cfIconSet = Nothing cfColorScale = Nothing targetSheet = Nothing ' Close the Workbook object. If Not newWorkbook Is Nothing Then newWorkbook.Close(False) newWorkbook = Nothing End If ' Close the ApplicationClass object. If Not excelApplication Is Nothing Then excelApplication.Quit() excelApplication = Nothing End If GC.Collect() GC.WaitForPendingFinalizers() GC.Collect() GC.WaitForPendingFinalizers()
The preceding sample code creates a workbook that contains a single worksheet named Conditional Formatting that contains the following data and conditionally formatted cells.
Conditional formatting makes it simple to highlight specific values or to identify values in a range. For example, conditional formatting can answer requests such as "Show me the top 10 percent of all sales for North America," or "Show me only Nancy's sales for the year." Excel 2007 provides several enhancements to conditional formatting. These include:
Three new visualizations that help with exploring large data sets, identifying trends and exceptions, and quickly comparing data: data bars, color scales, and icon sets.
A new user interface (UI) to add, remove, and manage conditional formats.
Many new conditional formatting rules.
The ability to use more than three conditions.
The ability to test conditions in addition to true or false.
Functionality specific to Microsoft PivotTables.
Functionality specific to tables.
This article explores how to programmatically set conditional formatting in Excel 2007. This next procedure reviews the steps.
To programmatically set conditional formatting in Excel 2007
Add to the project a reference to the Excel 12.0 Object Library. This marks that the project makes use of the Excel 12.0 Object Library.
Import the Microsoft.Office.Interop.Excel namespace. This allows code to use the classes and types exposed as part of the Microsoft.Office.Interop.Excel namespace without having to use the fully qualified namespace path.
Declare variables to hold references to the Excel 2007 objects that are used by the conditional formatting code and make method parameters easier to read.
Create a workbook and add a worksheet to it. This code shows how to create a workbook with a single worksheet in it.
Implement the conditional formatting code. This step shows code that illustrates how to apply color scale and icon set conditional formatting to a range of cells.