2

I'm having trouble with my loop not running throughout my entire sheet 1. If the value in Sheet 1 "tests" exist in sheet 2 "cancer". Then i want the value in sheet 2 "cancer" to be placed into sheet 1 "Tests". The code works except for the loop. Currently it only applies to the first record in my first sheet then stops.

Sub Testing()

Dim x As Long
Dim y As Long

x = 2
y = 2

Do While Sheets("Cancer").Cells(y, 1).Value <> ""
     If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) Then
           If Sheets("Tests").Cells(x, 4).Value = "" Then
                 Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
                 x = x + 1
           End If
     End If
     y = y + 1
Loop

End Sub
1
  • Have you stepped through the code to check what is going on? Commented Mar 30, 2017 at 15:14

2 Answers 2

2

I would use two for loops

for y = 2 to 10000 'the range your values are found
  if Sheets("Cancer").Cells(y, 1).Value <> "" then
    for x = 2 to 10000 'the range your values are in
      If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) and Sheets("Tests").Cells(x, 4).Value = "" Then
            Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))
      End If
    next
  end if
next

The reason for the loop not running throughout the entire sheet 1 is because of these two lines: If LCase(Trim(Sheets("Cancer").Cells(y, 1).Text)) = LCase(Trim(Sheets("Tests").Cells(x, 3).Text)) and Sheets("Tests").Cells(x, 4).Value = "" If these conditionals aren't both true, then x will never loop to its next iteration, and you'll have gone through looping through each value of Sheet2 "Cancer" while checking only the same record of Sheet1 "Tests".

Sign up to request clarification or add additional context in comments.

Comments

1

You've almost qualified all of your ranges. You missed one. Try changing the line:

Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))

to

Sheets("Tests").Cells(x, 4) = (Trim(Sheets("Cancer").Cells(y, 3).Text))

3 Comments

Good spot, but not sure that can be the original problem if the code works the first time.
You're right, I assumed it was changing the active sheet somewhere but it's not. Is it me, or is this just a vba simulation of a lookup?
Not sure tbh! Something like that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.