下一个循环没有停止的麻烦

时间:2018-01-29 00:24:05

标签: excel vba excel-vba for-loop infinite-loop

我正在尝试将包含等待列D 中的单元格的多张纸上的所有行复制到名为waiting的工作表中。这是代码。循环运行太远导致重复粘贴。我认为j = j + 1正在引起它,但我不知道如何纠正它。

Sub Waiting()

  ' unfilter entire workbook

   Dim sh As Worksheet

   For Each sh In Worksheets

      sh.AutoFilterMode = False
   Next sh

  ' copy rows to waiting sheet

  Dim c As Range
  Dim j As Integer
  Dim Target As Worksheet

  Set Target = ActiveWorkbook.Worksheets("Waiting")

  j = 1

  For Each sh In Worksheets
    For Each c In sh.Range("D1:D250")   ' Do 1000 rows
      If c = "waiting" Then
         sh.Rows(c.Row).Copy Target.Rows(j)
         j = j + 1
      End If
    Next c
  Next sh
 ' j=j+1 is causing infinite loop

End Sub

1 个答案:

答案 0 :(得分:1)

如果sh,您需要跳过sh.name = target.name

Dim c As Range
Dim j As Integer
Dim Target As Worksheet

Set Target = ActiveWorkbook.Worksheets("Waiting")
j = 1

For Each sh In Worksheets
    if sh.name <> target.name then
        For Each c In sh.Range("D1:D250")   ' Do 1000 rows
            If c = "waiting" Then
               sh.Rows(c.Row).Copy Target.Rows(j)
               j = j + 1
            End If
        Next c
    end if
Next sh