Skip to content

Commit dc39577

Browse files
[excel] (Formatting) Conditional formatting and user input sample (#642)
* Adding conditional formatting and parameter sample * Add link to new sample from user input article * Account for worksheet names with ! in them * Add entry to sample list on the overview * Apply suggestions from code review Co-authored-by: Elizabeth Samuel <[email protected]> --------- Co-authored-by: Elizabeth Samuel <[email protected]>
1 parent 3eb42fa commit dc39577

File tree

4 files changed

+97
-1
lines changed

4 files changed

+97
-1
lines changed

docs/develop/user-input.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,3 +113,4 @@ When adding input parameters and return values, consider the following allowance
113113

114114
- [Pass data to and from scripts in Power Automate](power-automate-parameters-returns.md)
115115
- [Run Office Scripts in Excel with buttons](script-buttons.md)
116+
- [Set conditional formatting for cross-column comparisons](../resources/samples/conditional-formatting-parameters.md)
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
---
2+
title: Set conditional formatting for cross-column comparisons
3+
description: Learn how to apply conditional formatting and get input from the user.
4+
ms.date: 09/07/2023
5+
ms.localizationpriority: medium
6+
---
7+
8+
# Set conditional formatting for cross-column comparisons
9+
10+
This sample shows how to apply conditional formatting to a range. The conditions used are comparing values to those in an adjacent column. Additionally, this sample uses [parameters to get user input](../../develop/user-input.md). This lets the person running the script select the range, the type of comparison, and the colors.
11+
12+
## Sample code: Set conditional formatting
13+
14+
```TypeScript
15+
/**
16+
* Formats a range on the current sheet based on values in an adjacent column.
17+
* @param rangeAddress The A1-notation range to format.
18+
* @param compareTo The adjacent column to compare against.
19+
* @param colorIfGreater The color of the cell if the value is greater than the adjacent column.
20+
* @param colorIfEqual The color of the cell if the value is equal to the adjacent column.
21+
* @param colorIfLess The color of the cell if the value is less than the adjacent column.
22+
*/
23+
function main(
24+
workbook: ExcelScript.Workbook,
25+
rangeAddress: string, compareTo: "Left" | "Right",
26+
colorIfGreater: "Red" | "Green" | "Yellow" | "None",
27+
colorIfLess: "Red" | "Green" | "Yellow" | "None",
28+
colorIfEqual: "Red" | "Green" | "Yellow" | "None"
29+
) {
30+
// Get the specified range.
31+
const selectedSheet = workbook.getActiveWorksheet();
32+
const range = selectedSheet.getRange(rangeAddress);
33+
34+
// Remove old conditional formatting.
35+
range.clearAllConditionalFormats();
36+
37+
// Get the address of the first adjacent cell of the adjacent column.
38+
let adjacentColumn: string;
39+
if (compareTo == "Left") {
40+
adjacentColumn = range.getColumnsBefore().getCell(0, 0).getAddress();
41+
} else {
42+
adjacentColumn = range.getColumnsAfter().getCell(0, 0).getAddress();
43+
}
44+
45+
// Remove the worksheet name from the address to create a relative formula.
46+
let formula = "=$" + adjacentColumn.substring(adjacentColumn.lastIndexOf("!") + 1);
47+
48+
// Set the conditional formatting based on the user's color choices.
49+
setConditionalFormatting(
50+
range.addConditionalFormat(ExcelScript.ConditionalFormatType.cellValue).getCellValue(),
51+
colorIfGreater,
52+
formula,
53+
ExcelScript.ConditionalCellValueOperator.greaterThan);
54+
setConditionalFormatting(
55+
range.addConditionalFormat(ExcelScript.ConditionalFormatType.cellValue).getCellValue(),
56+
colorIfEqual,
57+
formula,
58+
ExcelScript.ConditionalCellValueOperator.equalTo);
59+
setConditionalFormatting(
60+
range.addConditionalFormat(ExcelScript.ConditionalFormatType.cellValue).getCellValue(),
61+
colorIfLess,
62+
formula,
63+
ExcelScript.ConditionalCellValueOperator.lessThan);
64+
}
65+
66+
function setConditionalFormatting(
67+
conditionalFormat: ExcelScript.CellValueConditionalFormat,
68+
color: "Red" | "Green" | "Yellow" | "None",
69+
formula: string,
70+
operator: ExcelScript.ConditionalCellValueOperator
71+
) {
72+
// Pick the fill and font colors based on the preset color choices.
73+
if (color == "Red") {
74+
conditionalFormat.getFormat().getFont().setColor("#9C0006");
75+
conditionalFormat.getFormat().getFill().setColor("#FFC7CE");
76+
} else if (color == "Green") {
77+
conditionalFormat.getFormat().getFont().setColor("#001600");
78+
conditionalFormat.getFormat().getFill().setColor("#C6EFCE");
79+
} else if (color == "Yellow") {
80+
conditionalFormat.getFormat().getFont().setColor("#9C5700");
81+
conditionalFormat.getFormat().getFill().setColor("#FFEB9C");
82+
} else { /* None */
83+
return;
84+
}
85+
86+
// Apply the conditional formatting.
87+
conditionalFormat.setRule({
88+
formula1: formula,
89+
operator: operator
90+
});
91+
}
92+
```

docs/resources/samples/samples-overview.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ This section contains [Office Scripts](../../overview/excel.md) based solutions
3030
| [JavaScript `Date` samples](javascript-dates.md) | A collection of samples that show how to translate between JavaScript and Excel date formats. |
3131
| [Record day-to-day changes in Excel and report them with a Power Automate flow](report-day-to-day-changes.md) | This sample uses a scheduled Power Automate flow to record daily readings and report the changes. |
3232
| [Row and column visibility samples](row-and-column-visibility.md) | A collection of samples that demonstrate how to show, hide, and freeze rows and columns. |
33+
| [Set conditional formatting for cross-column comparisons](conditional-formatting-parameters.md) | This sample applies formatting based on values in adjacent columns. It also gets user input through script parameters. |
3334

3435
## Beyond the basics
3536

@@ -42,12 +43,12 @@ Check out the following end-to-end project that automates sample scenarios along
4243
| [Cross-reference workbooks](excel-cross-reference.md) | This sample uses Office Scripts and Power Automate to cross-reference and validate information in different workbooks. |
4344
| [Count blank rows in a specific sheet or in all sheets](count-blank-rows.md) | This sample detects if there are any blank rows in sheets where you anticipate data to be present and then report the blank row count for usage in a Power Automate flow. |
4445
| [Email chart and table images](email-images-chart-table.md) | This sample uses Office Scripts and Power Automate actions to create a chart and send that chart as an image by email. |
45-
| [External fetch calls](external-fetch-calls.md) | This sample uses `fetch` to get information from GitHub for the script. |
4646
| [Manage calculation mode in Excel](excel-calculation.md) | This sample shows how to use the calculation mode and calculate methods in Excel using Office Scripts. |
4747
| [Move rows across tables](move-rows-across-tables.md) | This sample shows how to move rows across tables by saving filters, then processing and reapplying the filters. |
4848
| [Output Excel data as JSON](get-table-data.md) | This solution shows how to output Excel table data as JSON to use in Power Automate. |
4949
| [Remove hyperlinks from each cell in an Excel worksheet](remove-hyperlinks-from-cells.md) | This sample clears all of the hyperlinks from the current worksheet. |
5050
| [Run a script on all Excel files in a folder](automate-tasks-on-all-excel-files-in-folder.md) | This project performs a set of automation tasks on all files situated in a folder on OneDrive for Business (can also be used for a SharePoint folder). It performs calculations on the Excel files, adds formatting, and inserts a comment that @mentions a colleague. |
51+
| [Use external fetch calls](external-fetch-calls.md) | This sample uses `fetch` to get information from GitHub for the script. |
5152
| [Write a large dataset](write-large-dataset.md) | This sample shows how to send a large range as smaller subranges. |
5253

5354
## Scenarios

docs/toc.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,8 @@ items:
9090
href: resources/samples/report-day-to-day-changes.md
9191
- name: Row and column visibility
9292
href: resources/samples/row-and-column-visibility.md
93+
- name: Set conditional formatting for cross-column comparisons
94+
href: resources/samples/conditional-formatting-parameters.md
9395
- name: Beyond the basics
9496
items:
9597
- name: Combine worksheets into a single workbook

0 commit comments

Comments
 (0)