使用VBA在Excel中添加新行

我有一个表格,其中包含以下文本(D#)的行:

  • D1
  • D2
  • D3

我需要在最后一个“D3”条目下添加一个新的“D4”行(将下一个整数附加到字母D)。 当然,下一次新的条目将是“D5”等…我怎样才能做到这一点使用VBA脚本或macros?

在列D中input以下工作表公式并将其扩展到整个区域:

="D" & ROW() 

您可以通过Excel VBAmacros将其自动化,如以下代码片段所示,该代码片段使用Worksheet公式填充Range("D1:D20")

 Range("D1:D20").Formula = "= ""D"" & Row()" 

对于您的特定任务,您可以考虑使用macroslogging器,然后“擦亮”VBA代码。

希望这会有所帮助。

使用它来find工作表上的最后一行:

 ColNum = 4 LastRow = ActiveSheet.Cells(Rows.Count, ColNum).End(xlUp).Offset(Abs(ActiveSheet.Cells(Rows.Count, ColNum).End(xlUp).Value <> ""), 0).Row 

LastRow的值将成为工作表中下一个打开的行。

引用代码中的单元格使用:

 ActiveSheet.Range("D" & Trim(Str(LastRow))).Value = "YourValue" 

或与索引:

 ActiveSheet.Range(Cells(LastRow, 4), Cells(LastRow, 4)).Value = "YourValue" 

这会填充给定工作表的给定列中的下一个单元格,其左侧的数字部分会加1

 Sub FillRow(ws As Worksheet, nCol As Long) Dim lastRow As Long With ws lastRow = .Cells(.Rows.Count, nCol).End(xlUp).row With .Cells(lastRow, nCol) .Offset(1).Value = "D" & Right(.Value, Len(.Value) - 1) + 1 End With End With End Sub