Excel VBA插入列标题&;列上的填充公式

Excel VBA插入列标题&;列上的填充公式,excel,vba,Excel,Vba,我想在E上插入新的列,在单元格E4中输入公式=(C4-B4)并填充到最后一行。在声明用于填充公式的单元格范围时,如何利用lastRow?我在.Autofill行收到运行时错误1004。您可以执行以下操作: 'Find the last used row in a Column: column A in this example Dim lastRow As Long With Worksheets("Summary") lastRow = .Cells(.Rows.Count, "

我想在E上插入新的列,在单元格E4中输入公式=(C4-B4)并填充到最后一行。在声明用于填充公式的单元格范围时,如何利用lastRow?我在.Autofill行收到运行时错误1004。

您可以执行以下操作:

'Find the last used row in a Column: column A in this example

Dim lastRow As Long


With Worksheets("Summary")
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

'Inserts column on E
Columns("E:E").Select
Selection.Insert Shift:=xlToRight

'Titles header "Net Return"
Range("E3").FormulaR1C1 = "Net Return"
'Places formula in cell E4
Range("E4").FormulaR1C1 = "=RC[-2]-RC[-3]"
'Fills formula down row - this is where my code breaks
Range("E4").AutoFill Destination:=Range("E4:(lastRow - 1)"), Type:=xlFillDefault

全新的空列中的“最后一行”是什么?这是如何确定的呢?好的,我想我的方法不会起作用,除非它根据A列确定最后一行,A列的行数总是最大的。我可以对a列执行最后一行检查,然后从中减去一行,并将其存储在最后一行?我不确定代码的外观为什么不仅仅是
范围(单元格(4,5),单元格(lastRow-1,5))。是否填写?或者,甚至可以跳过这一步,只在一个范围内进行:
Range(“E4:E”&(lastRow-1))。FormulaR1C1=“=RC[-2]-RC[-3]”
没有那么棘手,所以我相信你会明白的。任何时候,你发现自己用几个可变部分编码重复动作时,它可能会分解成一个独立的子项,你只需将可变项传递到其中即可。我必须将你的答案保存在文本文档中,以备将来参考。快速问题:我可以继续在SetUpSummarySheet()中插入其他列,它将在下一个子集中排序循环?是的,只需对要插入的其余列遵循相同的模式。如何从主子集中调用此子组合?只需调用
SetUpSummarySheet
Sub SetUpSummarySheet()

    Dim ws As Worksheet

    Set ws = Worksheets("Summary")

    InsertWithHeaderAndFormula ws, "E", "Net Return", "=RC[-2]-RC[-3]"
    InsertWithHeaderAndFormula ws, "G", "Blah", "=RC[-1]"
    'etc for other solumns

End Sub

'Insert a column in sheet ws, add a header hdr and a formula sForm to extend
'   as far down as there are values in ColA
Sub InsertWithHeaderAndFormula(ws As Worksheet, colLetter As String, _
                                hdr As String, sForm As String)

    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    ws.Cells(1, colLetter).EntireColumn.Insert Shift:=xlToRight
    ws.Cells(3, colLetter).Value = hdr
    ws.Cells(4, colLetter).Resize(lastRow - 3, 1).FormulaR1C1 = sForm

End Sub