【问题标题】:Exclude worksheets from loop with a list使用列表从循环中排除工作表
【发布时间】:2023-02-10 23:49:50
【问题描述】:

我在我的所有工作表中运行循环以收集第一个工作表上的数据。现在我想排除在第一个工作表的列表中按名称定义的工作表列表。

我可以像这样一一排除它们:

dim ws as worksheet
For each ws in ThisWorkbook.Worksheets
If ws.Name <> "Sheet1" and ws.name <> "Sheet2"

等等。

但 由于数据将来会发生变化,我不想每次“排除列表”发生变化时都编辑此代码。

【问题讨论】:

  • 保留一个包含排除的名称的列表,循环并检查每个名称。您可以按索引循环,但您需要知道排除的索引 - 有点复杂。

标签: excel vba


【解决方案1】:

处理活动工作簿的工作表,不包括指定范围内列表中的工作表:

将 A1:A6 地址修改为您的排除列表的位置。

Sub ProcessWorksheets()
    
    'declarations
    Dim ws As Worksheet
    Dim exceptionlist As Range
    
    'define range that contains exceptions
    Set exceptionlist = ActiveWorkbook.Worksheets("Sheet1").Range("A1:A6")
    
    'cycle through each worksheet
    For Each ws In ThisWorkbook.Worksheets
        'if ws.name does not exist in the range
        If Application.CountIf(exceptionlist, ws.Name) = 0 Then
            'do something with ws
            Debug.Print ws.Name
        Else
            'ignore it, do nothing
        End If
    Next

End Sub

【讨论】:

    【解决方案2】:

    您可以做的是创建一个名为 Exclude 的工作表。 在 A 列的第一行写 Exclude。 您之后要排除的其他工作表。最后,使用下面的代码..

    Dim Lastrow As Integer
    Lastrow = ws.Cells(Rows.Count, 1).End(xlUp).Row
    
    Set rs = ws.Range("A1:A1" & Lastrow)
    
    
    For Each ws In ThisWorkbook.Worksheets
        If Not rs.Find(ws.Name) Is Nothing Then
            'Your code
        End If
    Next
    

    【讨论】:

      猜你喜欢
      • 2021-08-03
      • 2022-11-16
      • 2012-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 2018-02-16
      相关资源
      最近更新 更多