VBA循环debugging – 下一个没有

基本上我试图复制和插入一定范围的细胞在第二张纸上,因为程序循环通过第一张纸上的单元格范围,只要细胞不是空的。 我需要复制和插入范围更改为每个循环新复制和插入的单元格。 任何帮助将非常感激

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,ij):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 

一条线你不需要With语句。 这将会更清洁。 还有两张纸,你应该使用两个纸张variables。 最后,我清理了你的Range(Cells, Cells)语法。 尽pipe如此,由于您的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 

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

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

你有两个wsvariables可能正确地开始你的代码。

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