2016-02-04 95 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