title | keywords | f1_keywords | ms.prod | api_name | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|---|
Range.SpecialCells method (Excel) |
vbaxl10.chm144203 |
vbaxl10.chm144203 |
excel |
Excel.Range.SpecialCells |
30c2035c-34e3-3b1a-f243-69a9fed97f3b |
05/11/2019 |
medium |
Range.SpecialCells method (Excel)
Returns a Range object that represents all the cells that match the specified type and value.
Syntax
expression.SpecialCells (Type, Value)
expression A variable that represents a Range object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Type | Required | XlCellType | The cells to include. |
Value | Optional | Variant | If Type is either xlCellTypeConstants or xlCellTypeFormulas, this argument is used to determine which types of cells to include in the result. These values can be added together to return more than one type. The default is to select all constants or formulas, no matter what the type. |
Return value
Range
Remarks
Use the XlSpecialCellsValue enumeration to specify cells with a particular type of value to include in the result.
Example
This example selects the last cell in the used range of Sheet1.
Worksheets("Sheet1").Activate ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Activate
[!includeSupport and feedback]
Home / VBA / How to use Special Cells Method in VBA in Excel
In VBA, the Special Cells method you can select a cell or range of cells that are of a specific type and have a specific sort of value. Let’s say you want to know that in the range A1:A10 which cells have a formula and have numbered as a value? Well, you can get this result with the SpecialCells method.
Here we are writing code to know the address of the cell which is used last from the range A1:A10. Note that, in the special cell method there are two arguments out of which one is required and the other is optional.
- First, declare a variable as range to store that cell address returned by the code.
- After that, refer to the range and use the “SpecialCells” method where you need to specify the “Type” argument with “xlCellTypeLastCell”.
- Next, set that special cell line of code to the variable that you have defined in the first step.
- From here, you need to use a VBA message box to get the address of the cells returns by the special cell method.
- In the end, use the address property with the variable to the get the address of the last type cell.
Here’s the full code.
Dim myRng As Range
Set myRng = Range("A1:A10").SpecialCells(xlCellTypeLastCell)
MsgBox myRng.Address
Now when you run this code, it will show you a message box with the address of the cell that has been used last (typed). So here in my case, I have used cell A10 and the same I got in the message box.
Select Cells with Notes
In Excel, old “Comments” are now “Notes”. When you write a code to select comments it will select the notes that you have in the range specified. Consider the following code.
Dim myRng As Range
Set myRng = _
Range("A1:A10").SpecialCells(xlCellTypeComments)
myRng.Select
Using Both of the Arguments
As I said earlier that you have two arguments in the SpecialCells method. Now, let’s see how you can use both arguments to select cells that have a formula, and that value that formula returns are a logical value.
Dim myRng As Range
Set myRng = Range("A1:A11").SpecialCells(xlCellTypeFormulas, xlLogical)
myRng.Select
Now when I run the above code, it selects the cells from the range A1 to A11 where I have formulas and a logical value.
Select Cells with Conditional Formatting
Range("A1:A11").SpecialCells(xlCellTypeSameFormatConditions)
Range("A1:A11").SpecialCells(xlCellTypeAllFormatConditions)
Select Visible Cells
And you can also select the visible using the “xlCellTypeVisible” constant. Consider the following code.
Dim myRng As Range
Set myRng = Range("A1:A11").SpecialCells(xlCellTypeVisible)
myRng.Select
Or you can also use the “12” as the argument value.
Dim myRng As Range
Set myRng = Range("A1:A11").SpecialCells(12)
myRng.Select
Cells with the Data Validation
Range("A1:A11").SpecialCells(xlCellTypeAllValidation)
Range("A1:A11").SpecialCells(xlCellTypeSameValidation)
More Tutorials
- Count Rows using VBA in Excel
- Excel VBA Font (Color, Size, Type, and Bold)
- Excel VBA Hide and Unhide a Column or a Row
- Excel VBA Range – Working with Range and Cells in VBA
- Apply Borders on a Cell using VBA in Excel
- Find Last Row, Column, and Cell using VBA in Excel
- Insert a Row using VBA in Excel
- Merge Cells in Excel using a VBA Code
- Select a Range/Cell using VBA in Excel
- SELECT ALL the Cells in a Worksheet using a VBA Code
- ActiveCell in VBA in Excel
- UsedRange Property in VBA in Excel
- VBA AutoFit (Rows, Column, or the Entire Worksheet)
- VBA ClearContents (from a Cell, Range, or Entire Worksheet)
- VBA Copy Range to Another Sheet + Workbook
- VBA Enter Value in a Cell (Set, Get and Change)
- VBA Insert Column (Single and Multiple)
- VBA Named Range | (Static + from Selection + Dynamic)
- VBA Range Offset
- VBA Sort Range | (Descending, Multiple Columns, Sort Orientation
- VBA Wrap Text (Cell, Range, and Entire Worksheet)
- VBA Check IF a Cell is Empty + Multiple Cells
⇠ Back to What is VBA in Excel
Helpful Links – Developer Tab – Visual Basic Editor – Run a Macro – Personal Macro Workbook – Excel Macro Recorder – VBA Interview Questions – VBA Codes
What are Specialcells?
Specialcells are a group of cells that belong to the same data type/format/color or have the same type of content like comments or blank. They are defined and used as a range object. This feature is useful when a change has to be done in several similar cells across a sheet.
For example, you can:
- Change all numbers to currencies/dates in an Excel sheet
- Remove rows with blank cells in a specific column
- Find and replace values
- Color, underline, or format all text data in a sheet
…and much more.
Syntax:
<Expression> . SpecialCells(Type:= <Type> , Value:= <Value> )
Or
<Expression> . SpecialCells( <Type> , <Value> )
Where:
- Expression can be a defined range object. E.g.:
- Cells
- Range(“A5:E15”)
- Application.UsedRange
- Type can be any one of the below mentioned types:
- xlCellTypeAllFormatConditions (refers to all cells that are formatted)
- xlCellTypeAllValidation (refers to all cells that contain datavalidation)
- xlCellTypeBlanks (refers to all cells that are blank)
- xlCellTypeComments (refers to all cells with notes/comments inserted)
- xlCellTypeConstants (refers to all cells that contain constants (either numbers or text) )
- xlCellTypeFormulas (refers to all cells that contain some formulas)
- xlCellTypeLastCell (refers to the last cell in all used ranges)
- xlCellTypeSameFormatConditions (refers to all cells with the same formatting as well as conditional formatting)
- xlCellTypeSameValidation (refers to all cells with the same set of datavalidation rules)
- xlCellTypeVisible (refers to all cells that are visible)
A combination of more than one of the types pointed above can also be used.
<Value>
can be anything specific to the mentioned datatype (options under point 2)
E.g. constants can either be:
- xlTextValues
- xlNumbers
How to Use Specialcells with Examples
Specialcells with Numbers
Let us try to find the number of bank customers who are deposit a principal amount in the bank for exactly four years.
Here is a piece of code that will loop through the range of cells from B2 to B12 that contain numbers. There is a counter that keeps incrementing if the cell that is looped through contains the value “4.”
Sub special_cells() 'setting the variable value initially Count = 0 'looping through a range of Cells For Each cell In Range("B2:B12").SpecialCells(xlCellTypeConstants, xlNumbers) 'Printing each cell value Debug.Print cell.Value 'Incrementing count if a cell with value "4" is found If Trim(cell.Value) = 4 Then Count = Count + 1 End If Next ' Finally display the no of cells with value "4" MsgBox Count End Sub
Here is the output that shows the number of customers who deposit for four years in a message box:
The immediate window screenshot also clearly shows that cells in the range that did not contain numbers have been ignored because we had called that out using the specialcells method.
Deletion of Blank Rows
In the same example explained above, let us delete the rows with blank cells in the “No. of Years” column.
Sub remove_blankrows() ' within the mentioned range if the cell identified is blank, the the entire row of that cell is deleted. Range("B2:B12").SpecialCells(xlCellTypeBlanks).EntireRow.Delete End Sub
On running the above code on the same example, we can see that the row with a blank cell (row number 11) has been deleted.
Counting Logical Values
Logical values are still considered constants. In this example, we consider a range of cells that contain just Boolean values i.e. True and False.
Sub special_cells_demo() 'setting the variable value initially Count = 0 'looping through a range of Cells For Each cell In Range("A2:A7").SpecialCells(xlCellTypeConstants, xlLogical) 'Printing each cell value Debug.Print cell.Value 'Incrementing count if a cell with value "true" is found If Trim(cell.Value) = True Then Count = Count + 1 End If Next ' Finally display the no of cells with value "4" MsgBox Count End Sub
Output:
The Boolean/logical value “True” is repeated four times in the range that has been called out in our code. Hence the message box has finally displayed “4.”
The immediate window here shows all the values that the “For loop” has considered as part of this range.
No Cells are Found: Error
If the range that we specify for specialcells do not fall under the criteria specified under type and value, then we’ll hit an error.
For example, in the same example mentioned above, if we change the range from A12 to A17, which are blank cells, then we will encounter a runtime error as the specialcells are looking for logical values in a blank range.
In the same code snipped used for the previous example, replace the line of code that refers to the range. And ensure that the range you mention in the code does not contain any data.
For Each cell In Range("A12:A17").SpecialCells(xlCellTypeConstants, xlLogical)
To overcome this error, we can use the “On Error Resume Next” statement.
Coloring Cells That Contain Specific Text
Here is another example of some text in a table. It is about ICC Men’s Cricket World Cup Winners—50 Overs.
Let us format all the cells that have “England” as the text.
First, we loop through all the cells of the entire sheet that have text. Then inside the loop we check if the text value is “England”. If yes, we color the font blue.
Sub special_cells_constants () ' loop through all the cells containing text data For Each cell In Application.Cells.SpecialCells(xlCellTypeConstants, xlTextValues) ' If value is "England" then colour it in blue. The colour index 5 stands for blue If cell.Value = "England" Then cell.Font.ColorIndex = 5 End If Next End Sub
Formatting the Numbers
Here is an example where the marks of students are converted into percentages.
Sub spl_cells2() ' convert all cells with numbers in column B to Percentage format Range("B:B").SpecialCells(xlCellTypeConstants, xlNumbers).Style = "Percent" End Sub
Can you see that the percentage conversion is not what we expected? It is necessary to divide the numbers by 100 before/after converting them to the percentage style. So, let’s update the code.
Sub spl_cells2() ' divide all numbers in the said range by 100 in order to convert it to percentage. For Each cell In Range("B:B").SpecialCells(xlCellTypeConstants, xlNumbers) cell.Value = cell.Value / 100 Next ' convert all cells with numbers in column B to Percentage format Range("B:B").SpecialCells(xlCellTypeConstants, xlNumbers).Style = "Percent" End Sub
Output: Finally, we converted the marks properly.
Defining a Range Object and Using it Throughout the Code
It is also possible to define a range of specialcells and use the range object wherever required instead of using the lengthy code to define it every time.
Examples:
In one of the examples discussed above, we are defining the numbers in the range twice. Instead, it can be defined once and used many times.
Sub spl_cells2() ' declare a range object Dim rng As Range ' define the range object Set rng = Range("B:B").SpecialCells(xlCellTypeConstants, xlNumbers) ' divide all numbers in the said range by 100 in order to convert it to percentage. For Each cell In rng cell.Value = cell.Value / 100 Next ' convert all cells with numbers in column B to Percentage format ' change number to percentage format rng.Style = "Percent" ' set font colour to pink rng.Font.ColorIndex = 7 ' increase the size of font to 15 rng.Font.Size = 15 ' apply italics style to the font rng.Font.Italic = True ' make the text look bold rng.Font.Bold = True End Sub
Using the code above, we have formatted the numbers in the range using the “range object” easily.
Output:
We can also wrap this formatting code within the with statement to reduce the lines of code/maintain the code easily.
Conclusion:
The specialcells function in VBA is a great help and a time saver when we want to work on a huge amount of data. It can help a lot on formatting/validating cells of the same type. This feature can be widely used in reporting and clean-up of data in Excel.
The only drawback is that we will not be able to reverse the actions performed using the VBA code. Hence, we need to be cautious of what we want to achieve as the impact will be irreversible and huge (in case of a large amount of data). One suggestion to overcome this problem is to create a backup before running the developed code, even if you are a great techie, and good at building data logic.
Содержание
- Range.SpecialCells method (Excel)
- Syntax
- Parameters
- Return value
- Remarks
- Example
- Support and feedback
- Метод Range.SpecialCells (Excel)
- Синтаксис
- Параметры
- Возвращаемое значение
- Замечания
- Пример
- Поддержка и обратная связь
- SpecialCells Method [Excel 2003 VBA Language Reference]
- XlCellType
- XlSpecialCellsValue
- Example
- Макрос поиска видимых строк и заполненных ячеек на листе Excel
- Комментарии
- SpecialCells in VBA
- How to use SpecialCells method in Excel VBA
Range.SpecialCells method (Excel)
Returns a Range object that represents all the cells that match the specified type and value.
Syntax
expression.SpecialCells (Type, Value)
expression A variable that represents a Range object.
Parameters
Name | Required/Optional | Data type | Description |
---|---|---|---|
Type | Required | XlCellType | The cells to include. |
Value | Optional | Variant | If Type is either xlCellTypeConstants or xlCellTypeFormulas, this argument is used to determine which types of cells to include in the result. These values can be added together to return more than one type. The default is to select all constants or formulas, no matter what the type. |
Return value
Use the XlSpecialCellsValue enumeration to specify cells with a particular type of value to include in the result.
Example
This example selects the last cell in the used range of Sheet1.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
Метод Range.SpecialCells (Excel)
Возвращает объект Range , представляющий все ячейки, соответствующие указанному типу и значению.
Синтаксис
expression. SpecialCells (Тип, Значение)
выражение: переменная, представляющая объект Range.
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
Тип | Обязательный | XlCellType | Ячейки для включения. |
Значение | Необязательный | Variant | Если тип имеет значение xlCellTypeConstants или xlCellTypeFormulas, этот аргумент используется для определения типов ячеек, которые следует включить в результат. Эти значения можно сложить вместе, чтобы вернуть несколько типов. По умолчанию выбираются все константы или формулы независимо от типа. |
Возвращаемое значение
Замечания
Используйте перечисление XlSpecialCellsValue , чтобы указать ячейки с определенным типом значения для включения в результат.
Пример
В этом примере выбирается последняя ячейка в используемом диапазоне Sheet1.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
SpecialCells Method [Excel 2003 VBA Language Reference]
Returns a Range object that represents all the cells that match the specified type and value. Range object.
expression.SpecialCells(Type, Value)
expression Required. An expression that returns one of the objects in the Applies To list.
XlCellType
XlCellType constants | Value |
---|---|
xlCellTypeAllFormatConditions. Cells of any format | -4172 |
xlCellTypeAllValidation. Cells having validation criteria | -4174 |
xlCellTypeBlanks. Empty cells | 4 |
xlCellTypeComments. Cells containing notes | -4144 |
xlCellTypeConstants. Cells containing constants | 2 |
xlCellTypeFormulas. Cells containing formulas | -4123 |
xlCellTypeLastCell. The last cell in the used range | 11 |
xlCellTypeSameFormatConditions. Cells having the same format | -4173 |
xlCellTypeSameValidation. Cells having the same validation criteria | -4175 |
xlCellTypeVisible. All visible cells | 12 |
XlSpecialCellsValue
XlSpecialCellsValue constants | Value |
---|---|
xlErrors | 16 |
xlLogical | 4 |
xlNumbers | 1 |
xlTextValues | 2 |
Example
This example selects the last cell in the used range of Sheet1.
Источник
Макрос поиска видимых строк и заполненных ячеек на листе Excel
Если ваш макрос выдаёт ошибку при использовании метода SpecialCells — возможно, причина в установленной защите листа Excel.
Почему разработчики Microsoft отключили работу этой функции на защищённых листах — не совсем понятно, но мы попробуем обойти это ограничение.
Итак, нам надо получить все заполненные ячейки из некого диапазона листа Excel.
Обычно для этого используется вызов метода SpecialCells — например,
Но на защищенном листе такой код выдаст ошибку 1004.
Чтобы избавиться от ошибки, мы используем функцию SpecialCells_TypeConstants — замену встроенному методу SpecialCells(xlCellTypeConstants)
Теперь наш код (работающий в т.ч. и на защищённых листах) будет выглядеть так:
Аналогичная функция, если нам надо получить диапазон видимых (нескрытых) строк на листе Excel:
(замена для SpecialCells(xlCellTypeVisible))
Комментарии
Игорь, добрый день.
Код безусловно полезный, но перебор ячеек на листе с парой-тройкой сотен тысяч строк и несколько десятков столбцов будет занимать много времени. Возможно стоит ограничить перебор, разбив его хотя бы на 2 части: найти вначале крайний справа столбец и последнюю строчку. После чего обрабатывать выбранный диапазон.
Что касается определения столбца применяя UsedRange — столкнулся с проблемой: если на «свежем» листе выполнить х=Sheets(SheetsName).UsedRange.Column + Sheets(SheetsName).UsedRange.Columns.Count , то количество столбцов отобразится корректно, если удалить несколько столбцов (и не переоткрывать с сохранением книгу), то диапазон берется как до удаления столбцов. Применение SpecialCells у меня не всегда дает корректный результат (ячейки разнородные по наполнению и когда попадается с ошибкой (битая ссылка), Excel воспринимает её буквально :)). По этой причине предлагаю вариант такой — брать через UsedRange и потом «минусовать» пустые столбцы в обратном порядке. Аналогично со строками.
А какое отношение ваш вопрос имеет к теме статьи?
Можно формулу написать, выводящую пропущенное число, можно то же самое сделать макросом, — вариантов много.
у меня вопрос как сделать так чтоб Excel мог автоматический находить на листе ошибки, к примеру если на листе идет последовательность чисел 1,2,3,5,6,7-получается что цифры 4 нет в списке, и как сделать что Excel мог автоматический показывать что такого числа нет тоесть указывать на эту ошибку?
Источник
SpecialCells in VBA
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.
Cells.SpecialCells(xlCellTypeConstants, xlTextValues).Font.ColorIndex=3
This VBA line will change the font colour to red for all text in the active worksheet.
The SpecialCells Method syntax is;
expression.SpecialCells(Type, Value)
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!
Источник
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.
Cells.SpecialCells(xlCellTypeConstants, xlTextValues).Font.ColorIndex=3
This VBA line will change the font colour to red for all text in the active worksheet.
The SpecialCells Method syntax is;
expression.SpecialCells(Type, Value)
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.
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!