Excel iterate through worksheets

2020-03-24 08:35发布

I have a workbook with many sheets and into some I need to enter a value if the preceding cell matches a given string.

My code works for the sheets I need it to but it errors out when it reaches some non desired sheets (that also have data in them).

The line the Debugger highlights is For Each r In Intersect (ActiveSheet.UsedRange, Range("F:F") I'm a newbie with VBA/Excel scripting. Sorry if this is blindingly obvious but I searched the site and couldn't find an answer that fit, or I just didn't recognize it.

Sub AllOnePool()
    Dim myStr As String
    Dim myPool As String
    Dim sh As Worksheet
    Dim xlCalc As XlCalculation

    myStr = InputBox(Prompt:="Input the Target Serial Number: e.g. 93127")
    myPool = InputBox(Prompt:="Input the Pool to Use: ")

    For Each sh In ActiveWorkbook.Worksheets
        sh.Activate
        For Each r In Intersect(ActiveSheet.UsedRange, Range("F:F"))
            If r.Text = myStr Then
                r.Offset(0, 1) = myPool
            End If
        Next r
    Next sh

End Sub

1条回答
We Are One
2楼-- · 2020-03-24 09:15

You need to check that the 2 ranges intersect:

Sub AllOnePool()
    Dim myStr As String
    Dim myPool As String
    Dim sh As Worksheet
    Dim cel As Range
    Dim xIng As Range

    myStr = InputBox(Prompt:="Input the Target Serial Number: i.e. 93127")
    myPool = InputBox(Prompt:="Input the Pool to Use: ")

    For Each sh In ActiveWorkbook.Worksheets
        With sh
            Set xIng = Intersect(.UsedRange, .Range("F:F"))
            If Not xIng Is Nothing Then
                For Each cel In xIng
                    If cel.Text = myStr Then cel.Offset(0, 1) = myPool
                Next
            End If
        End With
    Next
End Sub
查看更多
登录 后发表回答