excel 如果在VBA中满足某个条件,当我尝试循环遍历电子表格并筛选列时,循环不起作用

tf7tbtn2  于 2023-05-01  发布在  其他
关注(0)|答案(3)|浏览(108)

**更新!感谢所有对我的问题做出贡献的人。问题解决了!

我的循环不起作用,但我的if语句在活动电子表格上起作用。我已经绕着它玩了几个小时了,我似乎不能弄清楚。循环将继续循环访问同一活动工作表,而不是循环访问工作簿中的所有电子表格。

Sub WorksheetLoop()
    Dim WS_Count As Integer
    Dim I As Integer

    
    WS_Count = ActiveWorkbook.Worksheets.Count

         ' Begin the loop.
    For I = 1 To WS_Count
    'For Each Ws In Workbooks
    
        If WorksheetFunction.Sum(Range("N:N")) > 20000 Then
        Range("A:P").AutoFilter Field:=7, Criteria1:="<> 0    

    End If
           
         Next I

End Sub

此VBA应该循环遍历所有图纸。如果列N的总和大于20,000,则列G将过滤出“0:”。接下来,它应该循环通过下一个电子表格.如果列N不大于20000,那么我希望它不做任何事情就移动到下一个电子表格。
我尝试了每个循环,我得到了与for循环相同的结果。

jvidinwx

jvidinwx1#

试试这个

Private Sub WorksheetLoop()
    Dim ws As Worksheet
    Dim WS_Count As Integer
    Dim I As Integer
    
    WS_Count = ActiveWorkbook.Worksheets.Count
         ' Begin the loop.
    For I = 1 To WS_Count
    'For Each Ws In Workbooks
        Set ws = ActiveWorkbook.Worksheets(I)
        If Application.WorksheetFunction.Sum(ActiveWorkbook.Worksheets(I).Range("N:N")) > 20000 Then
            ws.Range("N:N").AutoFilter Field:=1, Operator:=xlFilterValues, Criteria1:="<>0" 
        End If
    Next I

End Sub
eblbsuwk

eblbsuwk2#

一次过滤所有工作表

Option Explicit

Sub ApplyFilters()
    Const PROC_TITLE As String = "Apply Filters"
    On Error GoTo ClearError ' start error-handling routine
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim ws As Worksheet, Total
    
    For Each ws In wb.Worksheets
        With ws
            If .FilterMode Then .ShowAllData ' clear filters
            If .AutoFilterMode Then .AutoFilterMode = False ' avoid wrong cols.
            With .Range("A1").CurrentRegion ' assumes no empty rows or columns
                'Debug.Print .Address(0, 0)
                If .Rows.Count > 1 Then
                    Total = Application.Sum(.Columns("N") _
                        .Resize(.Rows.Count - 1).Offset(1))
                    If IsNumeric(Total) Then
                        If Total > 20000 Then
                            .AutoFilter 7, "<>0"
                        End If
                    End If
                End If
            End With
        End With
    Next ws

    MsgBox "Filters applied.", vbInformation, PROC_TITLE

ProcExit:
    Exit Sub
ClearError: ' continue error-handling routine
    MsgBox "Run-time error '" & Err.Number & "':" & vbLf & vbLf _
        & Err.Description, vbCritical, PROC_TITLE
    Resume ProcExit
End Sub
bfrts1fy

bfrts1fy3#

在每个循环处添加一行以激活相应的工作表:

WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
    For I = 1 To WS_Count
       'For Each Ws In Workbooks
           ActiveWorkbook.Sheets(I).Activate
           If WorksheetFunction.Sum(Range("N:N")) > 20000 Then
               ActiveSheet.Range("A:P").AutoFilter Field:=7, Criteria1:="<> 0    
           End If
     Next I

希望有帮助,再见

相关问题