如果指定列中有值,则突出显示行

时间:2014-12-19 12:20:38

标签: c# excel interop

我已经问过这个问题并在VBA宏中回答了这个问题。 它工作正常,但我现在真正想做的是我在c#中自动化而不是制作一个宏,并且必须填写坏列+值的特定范围。

目前我得到了这段代码:

public void HightlightErrors()
{
     Worksheet worksheet = (Worksheet)workbook.Sheets[1];
     Range last = worksheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
     Range myRange = worksheet.get_Range("A1", last);
     int lastUsedRow = last.Row;
     int lastUsedColumn = last.Column;
     for (int i = 1; i < lastUsedColumn; i++) //Check each column to see if it is less than 5% filled.
     {
          Range currentColumn = worksheet.Columns[i];
          double a = application.WorksheetFunction.CountA(currentColumn);
          if ((a / lastUsedRow * 100) < 5)
          {
                //This range contains less than 5% 
                //Here i need to find the cell that has a value and highlight the Row.
          }
      }
      Marshal.ReleaseComObject(last);
      Marshal.ReleaseComObject(myRange);
}   

但我似乎无法找到与使用Range.FindNext语句查找值相关的任何内容。所有教程和说明都使用特定的数字或单词。 我不能那么遥远,任何可以指引我朝正确方向前进的人呢?

1 个答案:

答案 0 :(得分:0)

我解决了问题,这是最终结果

public void HightlightErrors()
{
     Worksheet worksheet = (Worksheet)workbook.Sheets[1];
     Range last = worksheet.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
     Range myRange = worksheet.get_Range("A1", last);
     int lastUsedRow = last.Row;
     int lastUsedColumn = last.Column;
     for (int i = 1; i < lastUsedColumn; i++) //Check each column to see if it is less than 5% filled.
     {
         Range currentColumn = worksheet.Columns[i];
         double a = application.WorksheetFunction.CountA(currentColumn);
         if ((a / lastUsedRow * 100) < 5)
         {
              string columnChar = GetExcelColumnName(i);
              string redCondition = "=COUNTA($"+ columnChar + "2)>0";
              dynamic format = myRange.FormatConditions.Add(XlFormatConditionType.xlExpression, Formula1: redCondition);
              format.Interior.Color = 0x0000FF;
         }
      }
      Marshal.ReleaseComObject(last);
      Marshal.ReleaseComObject(myRange);
}   

get ExcelColumnName是这个方法:

    private string GetExcelColumnName(int columnNumber)
    {
        int dividend = columnNumber;
        string columnName = String.Empty;
        int modulo;

        while (dividend > 0)
        {
            modulo = (dividend - 1) % 26;
            columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
            dividend = (int)((dividend - modulo) / 26);
        } 
        return columnName;
    }