【问题标题】:Inserting Formula ONLY visible Cells仅插入公式可见单元格
【发布时间】:2016-05-14 14:33:12
【问题描述】:

我有 3 列中的数据

A B & C,其中过滤器在 A 列上处于活动状态,我想应用一个代码,以便将公式应用于 C 列 - 从第二个可见行到最后一个可见行。

这是我写的代码,但是如果我更改 Range("C:C") 或 Range("C2:C") 则不起作用

Sub Test()
Dim rng As Range 

Range("C1").Select

Set rng = Application.Intersect(ActiveSheet.UsedRange, Range("**C2:C2000**"))

rng.Select

Selection.Formula = "=RC[-1]+RC[-2]"

End Sub

【问题讨论】:

标签: vba excel


【解决方案1】:

如果AutoFilter method 处于活动状态,您的第一行可能包含列标题标签,并且数据位于其下方。 Range.CurrentRegion propertyWorksheet.UsedRange property 更适合这种情况。

Range.SpecialCells methodxlCellTypeVisible 将引用可见单元格。我发现工作表的SUBTOTAL function 提供了一种很好的非破坏性方法,可以在尝试访问之前查看 iof 是否存在可见单元格。

一些With ... End With statements 将帮助您逐步分离出您正在寻找的细胞。

Sub test()
    'note that not a single var is necessary

    With Worksheets("Sheet1")   '<~~ surely you know what worksheet you are on
        With .Cells(1, 1).CurrentRegion
            With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0) '<~~one row down
                If CBool(Application.Subtotal(103, .Cells)) Then
                    'there are visible cells
                    With .Columns(3).SpecialCells(xlCellTypeVisible)
                        .Cells.FormulaR1C1 = "=RC[-1]+RC[-2]"
                    End With
                End If
            End With
        End With
    End With

End Sub

我使用了 Range.FormulaR1C1 property(而不是您原来的 Range.Formula property)单,您使用的是 xlR1C1 而不是 xlA1 公式语法。

【讨论】:

  • 您好 Jeeped,非常感谢您的快速回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多