使用VBA自动填充(导入新导出时扩展公式)

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

情况如下。进口大出口槽的OLEDB连接。前40列为导出,接下来的10列包含帮助公式。

打开时,我希望它使用自动填充来复制公式,因此它们会影响新导出的内容。

我当前尝试使用的代码质量很低(录制的宏),这根本不是专业的,但是我正在尝试学习如何从头开始设置而不进行录制。

代码:

Sub Macro1()
Sheets("DumpFollowUp").Select
Range("AT128432").Select
Selection.End(xlDown).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.AutoFill Destination:=Range("AT128512:BN128787")
Range("AT128512:BN128787").Select
End Sub

因此,如上所述,列AT至BN包含我需要扩展的公式。刷新后,它将在“打开工作簿事件”中使用此宏,因此它可以正确扩展(已加载新的导出)。

excel vba
2个回答
0
投票

这是您尝试实施的非常基本的方法:

Sub FillDownFormulas()

Dim lr1 As Long, lr2 As Long
Dim rng As Range

With Sheet1 'Change to your sheets CodeName

    'Get last used rows
    lr1 = .Cells(.Rows.Count, "A").End(xlUp).Row
    lr2 = .Cells(.Rows.Count, "AT").End(xlUp).Row

    'Fill formulas down
    Set rng = .Range(.Cells(lr2, "AT"), .Cells(lr1, "BN"))
    rng.Formula = .Range(.Cells(lr2, "AT"), .Cells(lr2, "BN")).Formula

End With

End Sub

注意:根据哪种类型的公式及其数量,您可能需要在运行宏时将Application.Calculation打开。另外,这将阻止您再次从顶部填充公式。


0
投票

以下内容可能对您有帮助,我只是删除了所有Select语句:

Sub FillDown()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("DumpFollowUp")
'declare and set the worksheet you are working with, amend as required
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the last row with data on Column A
ws.Range("AT1:BN1").AutoFill Destination:=Range("AT1:BN" & LastRow)
'fill down from AT1:BN1 to the last row with data
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.