How to modify nested for loops to get the correct output.

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, then show value from Sheet 2 Column C in the Sheet 1 Column Y.

I have written the following code to achieve my objective.

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" & ws2.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
            Exit For
            End If

        Next
    Next
End Sub

Open in new window


it is not printing correct values in column Y in sheet1. This is illustrated with the following image.

sample-results-preview.jpg
Help requested in modifying the code.

Thanks

Sunil Kakkar
Sunil KakkarAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Roy CoxGroup Finance ManagerCommented:
Attach an example workbook
0
Sunil KakkarAuthor Commented:
Hi Roy_Cox

Please find attached the example workbook. Comparing Cell values with If.xlsm

Thanks
Sunil Kakkar
comaring-cell-values-with-if-.xlsm
0
regmigrantCommented:
looking at your sample numbers I believe you need to synchronise the loops so they are looking at the same row; at the moment you are comparing each cell in sheet1!x with every cell in sheet2!a so only the final result will appear in Y. - not the result that matches the specific row you are looking for - I am basing this on your required result for '90'

Try this

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" & ws2.Range("A" & Rows.Count).End(xlUp).Row)
          if cell2.row = cell.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
            Exit For
            End If
       endif
        Next
    Next
End Sub

Open in new window

0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Sunil KakkarAuthor Commented:
Dear regmigrant ,

I could look into the problem by debug.print which you are mentioning. But my level in VBA is elementary and I am not able to find the right way to synchronise the loops. Internet search also could not help me much.
Hoping for proper modification which may serve as my guideline for future as well for similiar type of applications which regularly occur.

Thanks,

Sunil Kakkar
0
regmigrantCommented:
I added a possible solution to my answer whilst you were posting that reply :)

I've realised that the exit for might cause a problem with that loop so needs modifying:

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
              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
          endif
    Next
    Next
End Sub
0
Sunil KakkarAuthor Commented:
Dear regmigrant ,

This line of code is giving syntax error Compiler error
       
  if cell2.row = cell.row and Foundone = False

Open in new window


Please suggest remedial measures.

Thanking You,

Sunil Kakkar
0
regmigrantCommented:
Sorry I missed 'Then' off the end of that line

here's your sample with the corrected attempt

However this gives the same result for '90' as you had in the sample - but your requested answer is not the first solution (row 5) but the last (row 7) - this is because we are exiting the interior loop as soon as we find a result (your original method used 'exit for' mine uses 'foundone').

you need to define what happens when two of the ranges in sheet2 can generate a result
Copy-of-comaring-cell-values-with-i.xlsm
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Sunil KakkarAuthor Commented:
Hi regmigrant,

Thanks a lot. Your proposed solution works like a charm.

Sunil Kakkar
0
Sunil KakkarAuthor Commented:
Very helpful and responsibe. Good Analytical approach.
0
regmigrantCommented:
Thanks Sunil, hope it progresses well
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Excel

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.