1
votes

As in https://www.ozgrid.com/VBA/special-cells.htm the author says:

when/if one specifies only a single cell (via Selection or Range) Excel will assume you wish to work with the entire Worksheet of cells.

My following code (See the result) does select a single cell and the .SpecialCells(xlConstants) method does operate on the entire sheet marking all the cells with a constant red. My question is, however, why selection.Value = 1000 only works only on the single selected cell ("A1"), instead of the whole worksheet (that is all the cells are filled with 1000), According to the logic applied to the .SpecialCells(xlConstants) method?

Sub stkOvflSep7()
    ' This sub marks red the cells with a constant
    ' The first cell is selected
    ' Some other cells are filled with constant
    Dim constantCells As Range
    Dim cell As Range

    Worksheets("Sheet5").Cells.Clear
    activesheet.Cells.Interior.Color = xlNone

    Range("c1:d4").Value = 2

    Range("a1").Select
    ActiveCell.Select
    selection.Value = 1000       ' The first cell is selected

    ' Set constantCells = Range("A1").SpecialCells(xlConstants)
    Set constantCells = selection.SpecialCells(xlConstants)
    For Each cell In constantCells
        If cell.Value > 0 Then
            cell.Interior.Color = vbRed  ' marks red the cells with a constant
        End If
    Next cell
End Sub
2
According to Microsoft; Range.SpecialCells Method (Excel)... Returns a Range object that represents all the cells that match the specified type and value. XlCellType Specifies the type of cells.GMalc

2 Answers

1
votes

A cell is a cell (and not the entire worksheet) for every property and method.

The speciality you quoted...

As in https://www.ozgrid.com/VBA/special-cells.htm the author says:

when/if one specifies only a single cell (via Selection or Range) Excel will assume you wish to work with the entire Worksheet of cells.

...is because in Excel you can either select a single cell or a range of cells, but you can't deselect everything. For that reason - and because searching and/or selecting specials-cells within a single cell isn't very useful - excel uses the complete sheet for these two functions (i'm not completely sure if there is another function) when only a single cell is selcted (or referenced as range). If more than one cell is selected/referenced excel uses these cells for searching. This is the same for running searches etc. manually on the sheet.

0
votes

You're not really doing the same thing as the linked article, since you are assigning to a variable, rather than selecting Range("A1").SpecialCells(xlConstants).

I suspect the usedrange version would work though.