从用户指定的行开始插入可变行数

时间:2013-10-14 17:03:43

标签: vba excel-vba insert excel

我需要允许用户指定开始在其数据集中插入空行的行。查询的其余部分似乎工作正常。我只是不确定如何合并这个最后一个变量。这是我到目前为止的代码。

Dim NumRowsToInsert As Long
Dim RowIncrement As Long
Dim ws As Excel.Worksheet
Dim LastRow As Long
Dim LastEvenlyDivisibleRow
Dim i As Long

NumRowsToInsert = InputBox("How many rows would you like to insert between each 
row of data?")     'any number greater than 0
RowIncrement = InputBox("How many rows of data between line inserts?")       'ditto
Set ws = ActiveSheet
With ws
    LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
    LastEvenlyDivisibleRow = Int(LastRow / RowIncrement) * RowIncrement
    If LastEvenlyDivisibleRow = 0 Then
        Exit Sub
    End If
    Application.ScreenUpdating = False
    For i = LastEvenlyDivisibleRow To 1 Step -RowIncrement
        .Range(i & ":" & i + (NumRowsToInsert - 1)).Insert xlShiftDown
    Next i
End With
Application.ScreenUpdating = True
End Sub

2 个答案:

答案 0 :(得分:0)

我想假设在10行数据中增加了4行和1行,你希望第一组和第二组包含4行,在它们之间插入1个空白行,最后一组包含2行剩下的数据。 这会在之前插入一行并完成剩下的工作

For i = LastEvenlyDivisibleRow **+ 1** To 1 Step -RowIncrement

如果您不想插入第一行,可以跳过循环的第一步:

For i = LastEvenlyDivisibleRow **+ 1** To 2 Step -RowIncrement

答案 1 :(得分:0)

为什么不直接要求用户使用InputBox告诉你哪一行与其他行一样?我更改了您的代码,以询问用户在哪一行开始,并将最后一个for循环设置为向上计数,而不是向1,而是向用户指定的行。您可能必须包含一些检查以确保用户未指定低于文档末尾的行,但原则应该是正确的。我还没有测试过这段代码,所以没有保证!

Dim NumRowsToInsert,FirstRow As Long
Dim RowIncrement As Long
Dim ws As Excel.Worksheet
Dim LastRow As Long
Dim LastEvenlyDivisibleRow
Dim i As Long

Do
  FirstRow = InputBox("Please indicate at which row you want to start.")
Loop until isnumeric(FirstRow) 'keeps on asking until they enter an actual number, otherwise the program will lose its mind when the user inputs a character

NumRowsToInsert = InputBox("How many rows would you like to insert between each row of data?")     'any number greater than 0
RowIncrement = InputBox("How many rows of data between line inserts?")       'ditto
Set ws = ActiveSheet
With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastEvenlyDivisibleRow = Int(LastRow / RowIncrement) * RowIncrement
If LastEvenlyDivisibleRow = 0 Then
    Exit Sub
End If
Application.ScreenUpdating = False
For i = LastEvenlyDivisibleRow To FirstRow Step -RowIncrement
    .Range(i & ":" & i + (NumRowsToInsert - 1)).Insert xlShiftDown
Next i
End With
Application.ScreenUpdating = True
End Sub