简体   繁体   English

VBA - 循环遍历列并插入一行

[英]VBA - Loop through column and insert a row

I just want to insert a new line in each row of a column (beginning with the third row below the header).我只想在一列的每一行中插入一个新行(从标题下方的第三行开始)。 But instead, the macro adds n-new columns in the third row, n being the number of rows in the column.但相反,该宏在第三行添加了 n 个新列,n 是该列中的行数。 I have another macro with the same loop to insert a hyperlink in each cell, which works absolute fine, now I am drawing a blank...我有另一个具有相同循环的宏来在每个单元格中插入一个超链接,它工作得很好,现在我正在画一个空白......

What could be the reason?可能是什么原因?

Sub InsertRows()

    Dim i As Integer
    Dim lRow As Integer
    lRow = Cells(Rows.Count, 3).End(xlUp).Row
    i = 3  

    Do

    Range("C" & i).Select


    ActiveCell.EntireRow.Insert

    i = i + 1
    Loop Until i > lRow


End Sub

Assuming you want to insert a new row at the beginning of any existing row and following the existing code logic, you could try the following (I don't pretend this to be the best way to do so) :假设您想在任何现有行开头插入新行并遵循现有代码逻辑,您可以尝试以下操作(我不假装这是最好的方法)

Sub InsertRows()

'Fully qualify your Range references
With Sheet1                 ' Using e.g. the project sheet's Code(Name)
    Dim lRow As Long
    lRow = .Cells(.Rows.Count, 3).End(xlUp).Row
    Dim i As Long
    i = 3
    'Define the resulting end row
    Dim eRow As Long
    eRow = 2 * lRow - i + 1

    Do
        .Range("C" & i).EntireRow.Insert
        i = i + 2                   ' increment in double steps
    Loop Until i > eRow
End With

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM