【问题标题】:VBA Insert Column Header & Fill Formula on ColumnVBA插入列标题并在列上填充公式
【发布时间】:2019-10-18 17:33:41
【问题描述】:
'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

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

【问题讨论】:

  • 全新空列中的“最后一行”是什么?那如何确定?
  • 好点,我想我的方法将不起作用,除非它根据 A 列确定最后一行,这将始终具有最大行数。我可以对A列执行最后一行检查并从中减去一个并将其存储在lastRow中?我不确定该代码的外观
  • 为什么不只是Range(Cells(4,5), Cells(lastRow-1, 5)).FillDown?或者,甚至可以跳过这一步,一步完成:Range("E4:E" & (lastRow-1)).FormulaR1C1 = "=RC[-2]-RC[-3]"

标签: excel vba


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 不是那么棘手,所以我相信你会弄明白的。每当您发现自己使用一些可变片段编写重复动作时,它可能会被分解成一个独立的子组件,您只需将可变条目传递到其中。
  • 我必须将您的答案保存在文本文档中以供将来参考。快速提问:我可以继续在 SetUpSummarySheet() 中插入其他列,它会在下一个 sub 中循环遍历它吗?
  • 是的,只需对要插入的其余列遵循相同的模式
  • 如何从主子中调用这种子组合?
  • 您只需致电SetUpSummarySheet
猜你喜欢
  • 1970-01-01
  • 2015-12-06
  • 1970-01-01
  • 2020-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多