1

Say I have EXCEL 1 column (100 rows) of integers with values between 1 and 10 (with lrow being the last row). With VB, I am trying to add the rows UP TO a given sum (ex:25) to FIND THE ROW when the given sum (or less if adding the last row will bring the sum to over 25) is achieved.

For i = 1 To lRow
       Do While sum < 25
            sum= sum+ Cells(i, 1).Value
            Cells(2, 5).Value = sum
        Next j
        i = j-1
    Loop
Next i

var j doesn't increment. It keeps adding the fist row. WHY?

note: I want to continue to add the rest of the rows starting with the end position (row) of the first iteration. The reason for why i=j-1 is there.

1
  • That code won't run because you have Next j with no corresponding For. Fix that first. Or post your real code. Commented Feb 23, 2018 at 15:46

2 Answers 2

2

You do not need two loops:

For i = 1 to lRow
    Sum =Sum + ActiveSheet.Cells(i, 1).Value
    If Sum >= 25 then exit for
Next i
ActiveSheet.Cells(2, 5).Value = sum
Msgbox "Stopped at Row: " & i

to continue down the column and get a print out every time it exceeds 25:

For j = 1 To lrow
    For i = j To lrow
        Sum = Sum + ActiveSheet.Cells(i, 1).Value
        If Sum >= 25 Then Exit For
    Next i
    ActiveSheet.Cells(i, 5).Value = Sum 
    Sum = 0   
    j = i
Next j
Sign up to request clarification or add additional context in comments.

Comments

0

I'd go like follows

For i = 1 To lRow
    sum = sum + Cells(i, 1).Value
    If sum <= 25 Then i25 = i
Next

so:

  • sum will store the total sum of the cells values

  • i25 will store the row at which the sum was 25, or less if the sum exceeds 25 at row i25+1

Comments

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.