Что такое specialcells vba excel

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.

  1. First, declare a variable as range to store that cell address returned by the code.
    2-declare-a-variable-as-range
  2. After that, refer to the range and use the “SpecialCells” method where you need to specify the “Type” argument with “xlCellTypeLastCell”.
  3. Next, set that special cell line of code to the variable that you have defined in the first step.
    3-use-the-specialcells-method
  4. From here, you need to use a VBA message box to get the address of the cells returns by the special cell method.
  5. In the end, use the address property with the variable to the get the address of the last type cell.
    4-vba-message-box-to-get-the-address

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

    In Excel VBA the above are the inbuilt objects you can call on. The ones in red are the ones I use most frequently. This is not to detract from the others, I just find myself going back to the same functions time and again.

    The construct in Excel VBA for SpecialCells is as follows:

    YourRange.SpecialCells(TypeofSpecialCells).ActiontoPerform

    Once you have the syntax it is just a matter of applying your particular problem to the code.

    Using SpecialCells With VBA

    The following Excel VBA code will copy all of the constants in Column A with the help of the specialcells method.

    Sub SPCellsConstants() ‘Excel VBA to copy the Constants in Col A

    Range(«A1», Range(«A65536»).End(xlUp)).SpecialCells(2).Copy

    End Sub

    The following Excel VBA will delete all of the blanks in Column A. It has an error trap in case there are no blanks in the chosen column. This will prevent the code from breaking if it cannot find blank cells.

    Sub SPCellsBlanks() ‘Excel VBA to delete the Blank cells in Col A
    On Error Resume Next ‘Traps instance where there may be no blank cells

    Range(«A1», Range(«A65536»).End(xlUp)).SpecialCells(4).EntireRow.Delete

    On Error GoTo 0
    End Sub

    Sub FilteredData() ‘Excel VBA to copy from one sheet to another sheet.

    Range(«A2:E» & Cells(Rows.Count, 1).End(xlUp).Row).Copy Sheet2.[a1]

    End Sub

    However, the above method will not work effectively when data is grouped or hidden. We can use the Special Cells command to isolate visible cells. In the following example we will go through three methods. The first of these is to capture the first visible cell of data in Column A.

    Sub Copy1stVisibleCell() ‘Excel VBA using SpecialCells

    Range(«A2», Range(«A» & rows.count).End(xlUp)).SpecialCells(12).Cells(1, 1).Copy sheet2.[A1]

    End Sub

    The second and more practical step is to capture all of the data in a particular Column where the data is visible. I have excluded the headings by starting the range in Row 2.

    Sub CopyAllVisibleCell() ‘Copies Visible Cells to Sheet2 A1 using Excel VBA

    Range(«A2», Cells(Rows.Count, «A»).End(xlUp)).SpecialCells(12).Copy sheet2.[A1]

    End Sub

    This method can be extended to a more specific group of Columns in the following VBA example from A to E.

    Sub CopyRegionofVisibleCell() ‘Excel VBA to copy from A to E.

    Range(«A2», Cells(Rows.Count, «E»).End(xlUp)).SpecialCells(12).Copy sheet2.[A1]

    End Sub

    Probably the most practical method is to capture all of the data in the current region which is visible and copy it to sheet 2. This method will exclude the headings.

    Sub MoveVisible() ‘Excel VBA to capture visible data.

    Range(«A1»).CurrentRegion.Offset(1).SpecialCells(12).Copy Sheet2.[a7]

    End Sub

    Turn all of the values in a Column Negative

    Turning values in a range from positive to negative can be done with vba quite easily. Put some numbers in Col A.

    Now in B1 put -1. Run the following VBA code over the file.

    Sub MakeNeg()

    [b1].Copy ‘Excel VBA using a Negative (1)
    Range(«A2», Range(«A65536»).End(xlUp)).SpecialCells(12).PasteSpecial , xlMultiply

    End Sub

    The xlMultiply will multiply all the values in a column or file by -1, making the data negative in one movement. I often do the same thing to multiply by 1000. It is a neat trick in Excel and one worth knowing about.

    Put 1000 in Cell B1 and run the code above. It will multiply everything by 1000.

    This is not using specialcells but is quite a smart way to update a static Excel range with VBA. Put -1 in A1 and some numbers between A10 and C20.

    Sub MakeNeg2() ‘Excel VBA using formula inside the VBA coding.

    [A10:C20]=[if(A10:C20<>»»,If(isnumber(A10:C20),A10:C20*A1,A10:C20),»»)]

    End Sub

    As with most things the use of specialcells is best when practiced.

    Содержание

    1. Range.SpecialCells method (Excel)
    2. Syntax
    3. Parameters
    4. Return value
    5. Remarks
    6. Example
    7. Support and feedback
    8. Метод Range.SpecialCells (Excel)
    9. Синтаксис
    10. Параметры
    11. Возвращаемое значение
    12. Замечания
    13. Пример
    14. Поддержка и обратная связь
    15. SpecialCells Method [Excel 2003 VBA Language Reference]
    16. XlCellType
    17. XlSpecialCellsValue
    18. Example
    19. Макрос поиска видимых строк и заполненных ячеек на листе Excel
    20. Комментарии
    21. SpecialCells in VBA
    22. 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:

    1. xlCellTypeAllFormatConditions (all formatted cells)
    2. xlCellTypeAllValidation (all cells with datavalidation)
    3. xlCellTypeBlanks (all blank cells)
    4. xlCellTypeComments (all cells with notes)
    5. xlCellTypeConstants (all cells containing constants (numbers or text))
    6. xlCellTypeFormulas (all cells with formulas)
    7. xlCellTypeLastCell ( The last cell in all used ranges)
    8. xlCellTypeSameFormatConditions (all cells with the same formatting also conditional formatting)
    9. xlCellTypeSameValidation (all cells with the same datavalidation)
    10. 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:

    1. xlCellTypeAllFormatConditions (all formatted cells)
    2. xlCellTypeAllValidation (all cells with datavalidation)
    3. xlCellTypeBlanks (all blank cells)
    4. xlCellTypeComments (all cells with notes)
    5. xlCellTypeConstants (all cells containing constants (numbers or text))
    6. xlCellTypeFormulas (all cells with formulas)
    7. xlCellTypeLastCell (The last cell in all used ranges)
    8. xlCellTypeSameFormatConditions (all cells with the same formatting also conditional formatting)
    9. xlCellTypeSameValidation (all  cells with the same datavalidation)
    10. 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.

    Capture

    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.

    Capture

    and after running the macro

    Capture2

    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!

    Понравилась статья? Поделить с друзьями:
  • Что такое speak word
  • Что такое ribbon в excel
  • Что такое source в excel
  • Что такое rfm анализ в excel
  • Что такое replace в excel