对于...到VBA循环没有结束?

时间:2015-08-12 10:17:57

标签: excel vba

我写了以下循环,

For X = 1 To N
    Rng.Offset(, -3).Resize(, 670).Copy
    Rng.Offset(1, -3).Insert Shift:=xlDown
Next X
i = i + N

应该从一行开始(由i定义),并根据N是新的行。如果N等于20,我希望此代码生成20个副本,然后移动到下一行。但是,在第1行,N = 3,复制/粘贴似乎一遍又一遍地发生。有什么建议吗?

对于上下文,整个代码如下:

Sub NuPubPrepare()

    Dim i As Long, k As Long, N As Long, Entry As Range, Rng As Range

    i = 2
    While i <= 400
        Set Entry = Range("K" & i)
        For k = Columns("K").Column To Columns("GB").Column Step 5
            Set Entry = Union(Entry, Cells(i, k))
        Next k
        Set Rng = Range("D" & i)
        N = Application.WorksheetFunction.CountA(Entry)

        If N = 1 Then
            i = i + 1
        Else
            For X = 1 To N
                Rng.Offset(, -3).Resize(, 670).Copy
                Rng.Offset(1, -3).Insert Shift:=xlDown
            Next X
            i = i + N 

        End If
    Wend
End Sub

因此,N将计算其中包含数据的单元格的数量(从Ki到GBi的每5个单元格),并且我正在尝试使脚本根据此数字插入新行。

1 个答案:

答案 0 :(得分:1)

这会按照你的要求行事。

Sub test()
Dim rng As Range
Dim ws As Worksheet: Set ws = ThisWorkbook.ActiveSheet
Set rng = ws.Range("1:1")
    For i = 1 To 5
        rng.Offset(1).Insert Shift:=xlDown
        rng.Copy
        rng.Offset(1).PasteSpecial xlPasteValues
    Next i
End Sub