Exit 'For Each' loop when certain condition is true

前端 未结 4 977
余生分开走
余生分开走 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:27

    With due respect to my seniors, I found that exit for approach is not synchronising the outer and inner loop properly in this case. I have worked out another approach which works properly and gives correct results. I stand to be corrected as may be my expertise in VBA is not to the level of my seniors and more experienced persons here.

      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)
    
             Foundone = False
             For Each cell2 In ws2.Range("A2:A" & ws2.Range("A" & Rows.Count).End(xlUp).Row)
               If cell2.Row = cell.Row And Foundone = False Then
                   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
                     Foundone = True
                   End If
               End If
         Next
         Next
     End Sub
    

提交回复
热议问题