I have written a macro to find blank cells from a certain range using SpecialCells method of excel range object.
When i am trying to execute following code i get a exception as “No cells found”.
Sub test()
Debug.Print Sheet1.Range("A1:D4").SpecialCells(xlCellTypeBlanks).Address
End Sub
Steps:-
- Open a new Excel instance.
- Press ALT + F11/ Open VBE
- Insert a new Module
- Paste the above code and run test macro as specified above.
Output Received:
Runtime Error ‘1004’. No Cells Found.
Output Expected:
$A$1:$D$4
Case 1:
Now if i do any operation of cell A1. Operation such as giving fill color, etc. Call the test() macro then it does not throw exception.
Output Received:
$A$1
Output Expected:
$A$1:$D$4
Case 2:
Suppose if i give any value in cell B3. Call the test() macro, exception is not thrown.
Output Received:
$B$1:$B$2,$A$1:$A$3
Output Expected:
$A$1:$D$4
Case 3:
If i try to edit value or fill the cell outside the range “A1:D4” for example E10 and execute test() method then it gives me the proper output.
Output Received:
$A$1:$D$4
Note: Execute each Case with a new excel instance.
The reason is
SpecialCells“looks” at theUsedRangewhen returning a range.So using
SpecialCellson an unused sheet will returnRuntime Error '1004'. No Cells Found.(As an aside always use error handling with SpecialCells)When you change cell A1, that becomes the sheets
UsedRange, hence your Case 1 return of “A1”The code below looks to return Range(“A1:D4”).SpecialCells(xlCellTypeBlanks) for
A1:A4A1:A4The sheet with the usedrange reset (which is effectively 1) – fails