动态自动填充/填充但起始范围未知

问题描述 投票:0回答:1

我正在寻找构建一个 VBA 代码,其中工作表的最后一行从 B 列到 H 列有公式,工作表的最后一行每次都会更改,并且需要将公式从 B 到 H 填充到第 40 行, IE。范围的末尾是 H40。

如何使代码动态化以选择 B 列中的正确单元格来自动填充公式?

    'Calculate Last Row in the Report
    Sheets("Result").Select
    LastRow = Range("B:B").SpecialCells(xlCellTypeLastCell).Row
    
    'Select and Drag Formula
    Range("B1").End(xlDown).Select
    Range(ActiveCell, ActiveCell.End(xlToRight)).Select
    Selection.AutoFill Range(Cells(LastRow, 2) & ":H40"), Type:=xlFillDefault

我还尝试了另一种方法,其中我会提到开始和结束范围,以便 VBA 更容易选择范围限制。

    Dim EndCell As Range
    Dim FillRange As Range
    
    Set the end cell of the range
    Set EndCell = Range("H40")
    
    'Define the range to autofill
    Set FillRange = Range(Cells(LastRow, 2), EndCell)
    
    'Autofill the range
    FillRange.AutoFill Destination:=FillRange.Resize(, 10), Type:=xlFillDefault
    'Set FillRange = Range("B" & LastRow & ":H40")
    'FillRange.AutoFill Destination:=FillRange, Type:=xlFillDefault

假设报告中包含公式的最后一行是第 9 行,那么公式将是

Selection.AutoFill Destination:=Range("B9:H40"), Type:=xlFillDefault

如何使代码动态化以选择 B 列中的单元格来自动填充公式?

代码给出的错误是“

AutoFill method of Range class failed
”。

excel vba
1个回答
1
投票

复制公式

Option Explicit

Sub CopyDownFormulas()

    Const WS_NAME As String = "Result"
    Const WS_COLUMNS As String = "B:H"
    Const LAST_ROW As Long = 40

    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Sheets(WS_NAME)
    
    Dim lCell As Range: Set lCell = ws.Columns(WS_COLUMNS) _
        .Find("*", , xlFormulas, , xlByRows, xlPrevious)
    If lCell Is Nothing Then Exit Sub ' no data
    
    Dim FirstRow As Long: FirstRow = lCell.Row
    If FirstRow >= LAST_ROW Then Exit Sub ' filled already
    
    Dim rg As Range
    With ws.Rows(FirstRow).Columns(WS_COLUMNS)
        Set rg = .Resize(LAST_ROW - .Row + 1)
    End With
    
    rg.Formula = rg.Rows(1).Formula
 
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.