How to use SpecialCells method in Excel VBA
SpecialCells in VBA is a really useful method to deploy in Excel. It returns a Range Object that only covers the type of cells you specify. You can use the SpecialCells in VBA Method to return a Range Object that only holds numbers, text, blank cells, formulae, cells with datavalidation, cells with conditional formatting, the last cell in the worksheet, cells with comments and all visible cells.
If you for example want to change formatting for all numbers in a worksheet you do not need more than one line in the Visual Basic Editor to do it.
Cells.SpecialCells(xlCellTypeConstants, xlNumbers).Style = “currency”
This line will change all numbers in the active worksheet to currency format. The Range object Cells is used to tell Excel that you want to look at all the cells and the special cells method to decrease it to in this example only constants (xlCellTypeConstants) and again to decrease it to only numbers the criteria xlNumbers is added to the SpecialCells Method.
Similar we can use the SpecialCells Method to return a Range Object that only holds text.
This VBA line will change the font colour to red for all text in the active worksheet.
The SpecialCells Method syntax is;
The Expression have to be a Range object such as Cells, Range(“A1:B200″), ActiveSheet.UsedRange etc.
The different types of special cells are:
- xlCellTypeAllFormatConditions (all formatted cells)
- xlCellTypeAllValidation (all cells with datavalidation)
- xlCellTypeBlanks (all blank cells)
- xlCellTypeComments (all cells with notes)
- xlCellTypeConstants (all cells containing constants (numbers or text))
- xlCellTypeFormulas (all cells with formulas)
- xlCellTypeLastCell (The last cell in all used ranges)
- xlCellTypeSameFormatConditions (all cells with the same formatting also conditional formatting)
- xlCellTypeSameValidation (all cells with the same datavalidation)
- xlCellTypeVisible (alll visible cells)
You can also use a combination of the above options.
Cells.SpecialCells(xlCellTypeConstants, xlNumbers).SpecialCells(xlCellTypeAllValidation).Font.Color = vbRed
This line of VBA code will add red font colour to all cells with numbers & Datavalidation.
The SpecialCells in VBA Method is also very powerful if you want to test your data in an If Then Else decision code.
SpecialCells in VBA
In the example above all numbers are tested in the active worksheet if the value is greater than 7500. If the test is true 10% is added. The For Each loop is only running through cells with numbers.
The SpecialCells in VBA Method can be very handy if you need to remove blank rows from you Excel lists or Excel databases.
and after running the macro
In the above example The SpecialCells Method finds all blank cells in the range from A3 to A27 and deletes the entire row.
You have a lot of variations you can use and you will find out that when you start using The SpecialCells method you will save a lot of lines in your macros!