自动填充不起作用

时间:2018-01-24 16:11:17

标签: vba excel-vba excel

我正在处理我的代码,我有这个来过滤行并在第一个过滤行中插入一个公式。使用该公式我希望它填充,但它只在第一个过滤的行中插入公式而不会填充。

Sub Cal()
dim LastRow as long
With Worksheets("Data")
.Range("$A$1:$AI$80000").AutoFilter Field:=1, Criteria1:= _
    "Actual"
.Range("$A$1:$AI$80000").AutoFilter Field:=2, Criteria1:="2018"
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

.AutoFilter.Range.Offset(2).SpecialCells(xlCellTypeVisible).Cells(1, 35).Select 'SELECTS THE FIRST cell in A after deleting
ActiveCell.FormulaR1C1 = "=SUM(RC[-12]:RC[-1])"
.AutoFilter.Range.Offset(2).SpecialCells(xlCellTypeVisible).Cells(1, 35).Select
Selection.FillDown
End With
End Sub

2 个答案:

答案 0 :(得分:1)

如下所示,而不是.FillDown,指定最后一列可见数据​​的范围,并偏移到下一列以在其中输入公式:

Sub Cal()
Dim LastRow As Long
    With Worksheets("Data")
        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        .Range("$A$1:$AI$" & LastRow).AutoFilter Field:=1, Criteria1:="Actual"
        .Range("$A$1:$AI$" & LastRow).AutoFilter Field:=2, Criteria1:="2018"
        'filter according to values specified
        Set fltrdrng = .Range("$AI$2:$AI$" & LastRow).SpecialCells(xlCellTypeVisible)
        'set the range of visible data on last column with data on your data-set
        fltrdrng.Offset(0, 1).FormulaR1C1 = "=SUM(RC[-12]:RC[-1])"
        'add the formula to the adjacent column by offsetting
    End With
End Sub

答案 1 :(得分:1)

这应该做你想要的。过滤后的数据自动填充非常危险。这将获取activecell地址,然后创建最后一个单元格地址(代码中的第80000行),然后将公式添加到可见范围内的每个单元格中。

Start = ActiveCell.address
arow = ActiveCell.Row
alen = Len(arow)
lcell = Left(Start, Len(Start) - alen) & "80000"
Range(Start & ":" & lcell).SpecialCells(xlCellTypeVisible).Formula = "=SUM(RC[-12]:RC[-1])"