【问题标题】:How to loop through all sheets but one?如何遍历除一张以外的所有工作表?
【发布时间】:2021-01-17 09:24:06
【问题描述】:

我想遍历工作表,如果满足内部条件,则将其复制到我的“Controle”工作表中。

我的代码在没有循环的情况下工作。

我的工作表“Controle”中有一个列表,其中包含所有工作表中的所有彩色单元格。代码必须跳过名称为“Controle”的工作表,因为我在这里将单元格复制到。

Sub Dubbelewaarden()
Dim cell As Range
Dim sht As Worksheet
For Each sht In Worksheets
    If Not sht.Name <> "Controle" Then
        For Each cell In Range("A2", Range("A2").End(xlDown))
            If cell.Interior.ColorIndex = 3 Then
                cell.EntireRow.Copy Destination:=Sheets("Controle").Range("A" & Rows.Count).End(xlUp).Offset(1)
            End If
        Next cell
    End If
Next sht

End Sub
```

【问题讨论】:

  • Range("A2", Range("A2").End(xlDown)) 没有工作表引用,因此将假定活动工作表并且这永远不会改变。也最好使用 end(xlup)。
  • 你能给我一个如何解决这个问题的例子吗?因为我真的试过了,但是我的工作簿又崩溃了……

标签: excel vba if-statement foreach


【解决方案1】:

这只是将循环变量绑定到工作表的情况,否则将假定活动工作表。网上有很多参考。

Sub Dubbelewaarden()

Dim cell As Range
Dim sht As Worksheet

For Each sht In Worksheets
    If sht.Name <> "Controle" Then
        'tie reference to sheet in loop
        For Each cell In sht.Range("A2", sht.Range("A" & Rows.Count).End(xlUp))
            If cell.Interior.ColorIndex = 3 Then
                cell.EntireRow.Copy Destination:=Sheets("Controle").Range("A" & Rows.Count).End(xlUp).Offset(1)
            End If
        Next cell
    End If
Next sht

End Sub

【讨论】:

  • 现在,如果我运行代码,它不再做任何事情。但是感谢您向我展示了如何将引用与工作表联系起来。
  • 我只是注意到您的 If 条件中有一个双重否定,因此只有在工作表名称为“Controle”时才会运行。
  • 现在,如果我运行您的代码,他复制的唯一表格是名为“uren”的第三张表格,非常奇怪。它只是看起来不会比那张纸或其他东西更远......但仍然感谢您的帮助!
  • 代码没有问题,所以发生了其他事情。
  • 您的代码运行良好!!谢谢您的帮助。问题出在我的另一个潜艇上!!
猜你喜欢
  • 1970-01-01
  • 2020-05-21
  • 1970-01-01
  • 1970-01-01
  • 2019-08-16
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多