Insert Specific Number of Rows

我的未来我决定 提交于 2020-05-13 18:19:09

问题


I'm trying to insert a specific number of rows. Right now I'm using the below code to insert 4 lines. I'm trying to write a line of code that will insert a certain number or rows based on a number in a certain cell. For example, if I wanted to insert 4 rows and cell A2 is the cell where I can change the number of rows I want to add, what code would I use to add any number of rows based off what number I insert in cell A2.

ActiveCell.EntireRow.Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown

回答1:


You can use something like the line below to insert 4 rows at once:

ActiveCell.EntireRow.Resize(4).Insert Shift:=xlDown 

or maybe the line below (depends on where you want the added rows to be added):

ActiveCell.EntireRow.Offset(1).Resize(4).Insert Shift:=xlDown

and without the need to use ActiveCell , which is always recommended:

Range("A2").EntireRow.Offset(1).Resize(4).Insert Shift:=xlDown



回答2:


This should work


Sub InsertRow()

  Dim ws As Worksheet
  Dim NBOFROWS As Range
  Set ws = ThisWorkbook.ActiveSheet

  With ws
    Set NBOFROWS = .Range("A2")
    ActiveCell.EntireRow.Offset(1).Resize(NBOFROWS.Value).Insert Shift:=xlDown
  End With

End Sub



来源:https://stackoverflow.com/questions/43525799/insert-specific-number-of-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!