Export (0) Print
Expand All
Expand Minimize

How to: Change Formatting in Worksheet Rows Containing Selected Cells

NoteNote

Some code examples in this topic use the this or Me keyword or the Globals class in a way that is specific to document-level customizations, or they rely on features of document-level customizations such as host controls. These examples can be compiled only if you have the required applications installed. For more information, see Features Available by Product Combination.

You can change the font of an entire row that contains a selected cell so that the text is bold. Call the following procedure from the SelectionChange event handler to change the format of the row.

To make the current row bold and the previously bolded row normal

  1. Declare a static variable to keep track of the previously selected row.

    static int previousRow = 0;
    
    
  2. Retrieve a reference to the current cell using the ActiveCell property.

    Excel.Range currentCell = this.Application.ActiveCell;
    
    
  3. Bold the current row using the EntireRow property of the active cell.

    currentCell.EntireRow.Font.Bold = true; 
    
    
  4. Ensure that the current value of previousRow is not 0, which indicates that this is not the first time through this code.

    if (previousRow != 0)
    
    
  5. Ensure that the current row is different from the previous row.

    if (currentCell.Row != previousRow)
    
    
  6. Retrieve a reference to a range representing the row selected previously and set that row to not be bold.

    Excel.Range rng = (Excel.Range)ws.Rows[previousRow, missing];
    rng.EntireRow.Font.Bold = false;
    
    
  7. Store the current row so that it can become the previous row on the next pass.

    previousRow = currentCell.Row;
    
    

The following example shows the complete method.

Example

// Keep track of the previously bolded row.
static int previousRow = 0;

private void BoldCurrentRow(Excel.Worksheet ws)
{
    // Work with the current active cell.
    Excel.Range currentCell = this.Application.ActiveCell;

    // Bold the current row.
    currentCell.EntireRow.Font.Bold = true; 

    // If a pass has been done previously, make the old row not bold.
    // Make sure previousRow is not 0 (otherwise this is your first pass through).
    if (previousRow != 0)
    
        // Make sure the current row is not the same as the previous row.
        if (currentCell.Row != previousRow)
        {
            Excel.Range rng = (Excel.Range)ws.Rows[previousRow, missing];
            rng.EntireRow.Font.Bold = false;
        }

    // Store the new row number for the next pass.
    previousRow = currentCell.Row;
}

See Also

Community Additions

ADD
Show:
© 2014 Microsoft