循环工作表并应用过滤器

时间:2019-02-13 20:45:31

标签: excel vba

当我遍历工作表并应用过滤器时,它只会添加来自第一个匹配工作表的收件人(B列),而不是随后的工作表。

Public Sub someFunction()

Dim recipients As String
Dim recipient As Range
Dim worksheet As worksheet

For Each worksheet In ActiveWorkbook.Worksheets
    Select Case worksheet.Name
        Case "ABC Group", "DEF Group"
            ' DO NOTHING
        Case Else
            Worksheets(Worksheet.Name).Activate
            colNum = Application.WorksheetFunction.Match("a column name", ActiveSheet.Rows(5), 0)
            Rows(5).AutoFilter Field:=colNum - 1, Criteria1:="=some string*"
            With ActiveSheet ' ThisWorkbook.Sheets("Sheet1") - Or ActiveSheet
                For Each recipient In .Range("B6:B" & .UsedRange.Rows.Count).SpecialCells(xlCellTypeVisible).Cells
                    recipients = recipients + recipient + ";"
                Next recipient
            End With
    End Select
Next
End Sub

不过,该过滤器已正确应用于所有匹配的工作表,并且在GUI中,代码在最终工作表上完成了。

1 个答案:

答案 0 :(得分:2)

您有一个工作表变量,请使用它!当明确定义工作表时,无需激活工作表。

您应该将工作表变量更改为不匹配关键的VBA单词/对象。由于您的命名方法过于接近预定义的VBA对象,因此我将其更改为ws

此外,您可以使用&运算符而不是+来构建字符串


Option Explicit

Public Sub someFunction()

Dim mystring As String
Dim recipient As Range
Dim colNum As Long
Dim ws As Worksheet

For Each ws In ActiveWorkbook.Worksheets
    Select Case ws.Name
        Case "ABC Group", "DEF Group"
            ' DO NOTHING
        Case Else
            colNum = Application.WorksheetFunction.Match("a column name", ws.Rows(5), 0)
            ws.Rows(5).AutoFilter Field:=colNum - 1, Criteria1:="=some string*"

                For Each recipient In ws.Range("B6:B" & ws.UsedRange.Rows.Count).SpecialCells(xlCellTypeVisible).Cells
                    mystring = mystring & recipient & ";"
                Next recipient

    End Select
Next ws

mystring = Left(mystring, Len(mystring) - 1) '<-- Remove last instance of ";"

End Sub