通过具有多个for循环的工作表循环并且如果函数内部不起作用

时间:2018-06-15 10:04:04

标签: excel vba excel-vba

代码有效,但仅适用于当前工作表。我的目标是通过循环遍历所有工作表来运行功能代码。这段代码似乎没有循环。

Sub sbDelete_Rows_IF_Cell_Cntains_String_Text_Value()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
    Dim lRow As Long
    Dim iCntr As Long
    lRow = 200
    For iCntr = lRow To 1 Step -1
        If Cells(iCntr, 3) = "PUT" Or Cells(iCntr, 3) = "CALL" Or Cells(iCntr, 3) = "PRN" Then
            Rows(iCntr).Delete
        End If
    Next
Next ws
End Sub

如果我将ws标识添加到" Cells"我在" If"上出现了不匹配错误线。这里出了什么问题?

Sub sbDelete_Rows_IF_Cell_Cntains_String_Text_Value()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
    Dim lRow As Long
    Dim iCntr As Long
    lRow = 200
    For iCntr = lRow To 1 Step -1
        If ws.Cells(iCntr, 3) = "PUT" Or ws.Cells(iCntr, 3) = "CALL" Or ws.Cells(iCntr, 3) = "PRN" Then
            Rows(iCntr).Delete
        End If
    Next
Next ws
End Sub

1 个答案:

答案 0 :(得分:0)

总是声明父工作表(以及使用更多工作簿时的父工作簿)是一个好习惯:

Sub sbDelete_Rows_IF_Cell_Cntains_String_Text_Value()

    On Error GoTo sbDelete_Rows_IF_Cell_Cntains_String_Text_Value_Error

    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        With ws
            Dim lRow As Long
            Dim iCntr As Long
            lRow = 200
            For iCntr = lRow To 1 Step -1
                If .Cells(iCntr, 3) = "PUT" Or .Cells(iCntr, 3) = "CALL" Or .Cells(iCntr, 3) = "PRN" Then
                    .Rows(iCntr).Delete
                End If
            Next
        End With
    Next ws

   On Error GoTo 0
   Exit Sub

sbDelete_Rows_IF_Cell_Cntains_String_Text_Value_Error:

    MsgBox "Error " & Err.Number & " on cell " & Cells(iCntr, 3).Address

End Sub