VBA 循环调试 - Next Without For

VBA Loop Debugging - Next Without For

本质上,我试图在第二个 sheet 上复制并插入一定范围的单元格,因为程序循环遍历第一个 sheet 上的一系列单元格,只要单元格不为空即可。我需要复制和插入范围更改为每个循环的新复制和插入的单元格。任何帮助将不胜感激

Private Sub CommandButton1_Click()

    Dim ws As Worksheet
    Dim rng As Range
    Dim i As Integer
    Dim j As Integer

    For i = 12 To 24
        Set ws = ThisWorkbook.Sheets("Input")
        With ws
            If Not IsEmpty(Cells(i, 2)) Then
            For j = 10 To -2
                Set ws = ThisWorkbook.Sheets("Budget Output #2")
                With ws
                    Set rng = .Range("Cell(5,i-j):Cell(17,i-j+1)")
                    rng.Copy
                    rng.Offset(0, 2).Insert Shift:=xlToRight
                    rng.Offset(0, 2).ColumnWidth = 20
                    Application.CutCopyMode = False
            Next j
    Next i
            End If
                End With
        End With

End Sub

我会让你想出答案。这是正确的结构:

For i ....  
    For j ...  
       with ws
       end with
    next j
next i

一行不需要 With 语句。这样会干净很多。同样对于两个 sheet,您应该使用两个 sheet 变量。最后,我清理了你的 Range(Cells, Cells) 语法。虽然,由于您的 For j = 10 to -2,这仍然行不通。要向后移动,您必须使用 Step -#.

Private Sub CommandButton1_Click()

    Dim wsIn As Worksheet, wsOut As Worksheet
    Dim rng As Range
    Dim i As Integer
    Dim j As Integer

    Set wsIn = ThisWorkbook.Sheets("Input")
    Set wsOut = ThisWorkbook.Sheets("Budget Output #2")    

    x = 2
    For i = 12 To 24
        If Not IsEmpty(wsIn.Cells(i, 2)) Then
            Set rng = wsOut.Range("B:C")
            rng.Copy
            rng.Offset(0, x).Insert Shift:=xlToRight
            rng.Offset(0, x).ColumnWidth = 20
            Application.CutCopyMode = False
            x = x + 2
        End If
    Next i

End Sub

您有两个 ws 变量可能会正确启动您的代码。

  Dim ws As Worksheet, sh As Worksheet
    Set ws = Sheets("Budget Output #2")
    Set sh = Sheets("Input")