Well it took me a while but I think I've got there.
The problem is in your calculation of
endRow
and
startRow
When stepping through the code I couldn't understand why
r
(the loop counter) kept getting reset to 0. It is because it is declared as an integer but you are using
Rows.Count
in your loop which is a
Long
.
So step 1 is to use
Dim r As Long
Dim startRow As Long
Dim endRow As Long
However, the values are still not being calculated at this stage. Problem was in the comparison. So step 2 is to change
Range("B" & r)
to be
Range("B" & r).Value2
That got me as far as getting the
startRow
but endRow was coming up as 23 instead of 13. I tracked that one down to
ElseIf pID(x)
.
x
is undefined and so is defaulting to 0. I believe that should be
ElseIf pID(currProduct)...
You can avoid problems like that by using the following line at the top of your code module
Option Explicit
That got values appearing on the sheet, but it takes a long time!
Instead of using
Rows.Count
why not stop at the last populated row in the sheet e.g.
Dim lastRow As Long
lastRow = Me.UsedRange.Rows(Me.UsedRange.Rows.Count).Row
(Note - the
Me
assumes that this VBA code is on the Sheet that is being used - if you put this code into a basic module you will have to explicitly identify the sheet instead).
Also, instead of starting with
r=1
each time, initialise
endRow = 9
then always start that loop from
endRow + 1
. I ended up with something like this
endRow = 9
For currProduct = 1 To pID.Count
Dim lastRow As Long
lastRow = Me.UsedRange.Rows(Me.UsedRange.Rows.Count).Row
cStage = 0
For r = endRow + 1 To lastRow
If pID(currProduct) = Range("B" & r).Value2 And cStage = 0 Then
startRow = r
cStage = 1
ElseIf pID(currProduct) <> Range("B" & r).Value2 And cStage = 1 Then
cStage = 2
endRow = r - 1
End If
Next r
I didn't actually carry on looking into the next bit, but I suspect you can make it more efficient too. I will mention one last horror though
On Error Resume Next
Don't do it!