2016-02-04 101 views
0

我有3列插入公式只可见细胞

AB & C,其中一个过滤器是在列A活性的数据,我要应用代码,以便对列C被施加式 - 从第二个可见行直到最后一个可见行。

这是我写的代码,但是,如果我改变范围(“C:C”)这不工作或范围(“C: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 
+3

调查[specialcells()函数](https://msdn.microsoft.com/en-us/library/office/ff196157.aspx)。 –

回答

2

利用有效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你使用xlR1C1xlA1公式语法(而不是你原来Range.Formula property)单身。

+0

嗨Jeeped,非常感谢您的快速响应。 – Sas