【问题标题】:On the selection of a single cell关于单个单元格的选择
【发布时间】:2018-09-07 20:49:58
【问题描述】:

正如https://www.ozgrid.com/VBA/special-cells.htm作者所说:

当/如果一个人只指定一个单元格(通过选择或范围) Excel 将假定您希望使用整个工作表的单元格。

我的以下代码 (See the result) 确实选择了一个单元格,并且 .SpecialCells(xlConstants) 方法确实在整个工作表上运行,将所有单元格标记为恒定红色。但是,我的问题是,为什么 selection.Value = 1000 仅适用于单个选定的单元格(“A1”),而不是整个工作表(即所有单元格都填充 1000),根据应用于的逻辑.SpecialCells(xlConstants) 方法?

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

【问题讨论】:

  • 根据微软的说法; Range.SpecialCells 方法 (Excel)... 返回一个 Range 对象,该对象表示与指定类型和值匹配的所有单元格。 XlCellType 指定单元格的类型。

标签: vba excel


【解决方案1】:

单元格是每个属性和方法的一个单元格(而不是整个工作表)。

你引用的专业...

正如https://www.ozgrid.com/VBA/special-cells.htm作者所说:

当/如果只指定一个单元格(通过选择或范围)Excel 将假定您希望使用整个工作表的单元格。

...是因为在 Excel 中,您可以选择单个单元格或一系列单元格,但不能取消选择所有内容。出于这个原因 - 并且因为在单个单元格中搜索和/或选择特殊单元格不是很有用 - excel 使用这两个函数的完整工作表(我不完全确定是否有另一个函数)当只有一个单元格被选择(或引用为范围)。如果选择/引用了多个单元格,则 excel 将使用这些单元格进行搜索。这与在工作表上手动运行搜索等相同。

【讨论】:

  • 这种解释对我来说很有意义。非常感谢!
【解决方案2】:

您实际上并没有与链接的文章做同样的事情,因为您正在分配一个变量,而不是选择Range("A1").SpecialCells(xlConstants)

我怀疑 usedrange 版本会起作用。

【讨论】:

  • 如果我用 Set constantCells = selection.SpecialCells(xlConstants) 替换它,为什么操作员仍然无法仅处理该单个单元格,但它会在整个工作表上生效?这是否意味着赋值将选择标识为单个单元格,而 Range("A1").SpecialCells(xlConstants) 将其视为整个工作表?
猜你喜欢
  • 1970-01-01
  • 2021-02-08
  • 2014-07-17
  • 1970-01-01
  • 1970-01-01
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多