3
Answers

Check if Cells A2 and A3 are blank in Excel

richard smith

richard smith

11y
4.4k
1
I tried this code:

public static void CellsBlank()
{
Worksheet worksheet;
Workbook wb = Global.Variables.GlobalVariables.oXL.ActiveWorkbook;
Excel.Range cell1 = (Excel.Range)worksheet.get_Range("A2", "A2");
Excel.Range cell2 = (Excel.Range)worksheet.get_Range("A3", "A3");
}

But that throws a debug error when it hits my Excel.Range cell1 line!  How should I re-write this?
Answers (3)
0
Vulpes

Vulpes

NA 98.3k 1.5m 11y
Try:

public static bool CellsBlank()
{
   Worksheet worksheet;
   Workbook wb = Global.Variables.GlobalVariables.oXL.ActiveWorkbook;
   worksheet = wb.ActiveSheet;
   if (worksheet != null)
   {
     Excel.Range cell1 = worksheet.get_Range("A2", "A2");
     Excel.Range cell2 = worksheet.get_Range("A3", "A3");
     if(cell1.Value2 == null && cell2.Value2 == null)
     {
        return true;
     }
   }
   return false;
}
Accepted
0
Vulpes

Vulpes

NA 98.3k 1.5m 11y
Yes, except that since it's a method you need to specify the parentheses in C#:

if (CellsBlank())

Also, if you might want to test cells other than A2 and A3 , then you could pass them as parameters to the method.



0
richard smith

richard smith

NA 327 103.4k 11y
And to check the outcome in my code I would use:
if (CellsBlank == true)
{
//run the code for when cells are blank
}
else
//run the code for when cells are NOT blank
}

Is that correct?
Next Recommended Forum