Exit 'For Each' loop when certain condition is true

前端 未结 4 925
余生分开走
余生分开走 2021-01-14 17:14

I need to go over all rows on Sheet1 in Column X, grab its value and then, see if value is BETWEEN numbers combination stored on Sheet 2 columns A and B. If value is between

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-14 17:19

    In VBA you should just use the 'goto' command. EG:

    Sub FindBetweenIP()
    
        Dim ws1 As Worksheet
        Set ws1 = Sheets(1)
    
        Dim ws2 As Worksheet
        Set ws2 = Sheets(2)
    
        For Each cell In ws1.Range("X2:X" & ws1.Range("X" & Rows.Count).End(xlUp).Row)
    
            For Each cell2 In ws2.Range("A2:A" & ws1.Range("A" & Rows.Count).End(xlUp).Row)
    
                ip_range1 = cell2.Value2
                ip_range2 = cell2.Offset(0, 1).Value2
                isp = cell2.Offset(0, 2).Value2
    
                If (cell.Value >= ip_range1 And cell.Value <= ip_range2) Then
                    cell.Offset(0, 1).Value2 = isp
                    GoTo ExitInnerLoop:
                End If
            Next
    ExitInnerLoop:
        Next    
    End Sub
    

提交回复
热议问题