Cell selection not moving to next row while using if then in excel vba code

Important Notice


Please note that on 14th December 2023 users will experience an expected outage whilst we make upgrades to our network. We anticipate this process may take a couple of hours and so we apologise in advance for any inconvenience.

  • Column Q contains numbers, and string"Group By". Column R contains both Names (against the cells containing string), and part numbers in other rows. I want to copy only the names from column R, if column Q is value= "Group By". I have written the following code.


    Sub WithDoWhileAndIf()

    Range("Q2").Activate

    Do While ActiveCell.Value <> ""


    For i = Q2 To Q1000

    If ActiveCell.Value = "Group By" Then

    ActiveCell.Offset(0, 1).Copy

    ActiveCell.Offset(0, -1).PasteSpecial Paste:=xlValue

    ActiveCell.Offset(0, 1).Activate

    ActiveCell.Offset(1, 0).Activate

    End If

    Next

    Loop

    End Sub


    It copies only the first row value, and then the selection is not moving down in column Q. Can anyone please help me to rectify the error?


    Thanks a lot


    GM

  • Wow, I have identified a solution for this. But, I want this to work only upto 1000 rows. Can experts please guide me to improve my code?


    Sub WithDoWhileAndIf()

    Range("Q2").Activate

    Do While ActiveCell.Value <> ""

    For i = Q2 To 1000

    If ActiveCell.Value = "Group By" Then

    ActiveCell.Offset(0, 1).Copy

    ActiveCell.Offset(0, -1).PasteSpecial Paste:=xlValue

    Application.CutCopyMode = False

    ActiveCell.Offset(0, 1).Activate

    ActiveCell.Offset(1, 0).Activate

    Else

    ActiveCell.Offset(1, 0).Activate

    End If

    Next

    Loop

    End Sub

  • Try something like this:


    Rory
    Theory is when you know something, but it doesn’t work. Practice is when something works, but you don’t know why. Programmers combine theory and practice: nothing works and they don’t know why

  • Your explanation and code do not match. Do you want to copy the names from Column R and paste in Column P when Column Q is "Group By", leaving the "Group By" still in Column Q?

    We now have a reputation system in place. If my reply helped please "Like" the reply by clicking the "Like" icon at bottom right of my reply.

  • Try this


    It will work for just the rows in Column Q that contain data, so can extend beyond 1000 rows if your database grows in the future.


    It is also an array based code that will run faster than an object based code, especially if the database is large.

    We now have a reputation system in place. If my reply helped please "Like" the reply by clicking the "Like" icon at bottom right of my reply.

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!