0

Haven't had any luck trying to find an answer to the following and the code I've come up with is just horrible.

I'm trying to select a range of cells that sum to a specific value.

Column A are Room Numbers Column B is time in minutes spent to clean each room.

enter image description here

I'm looking for a way to loop through column B until their summed value is = or < 200

And then select the corresponding Rooms in Column A (Which will then be move to another sheet)

Does anyone have a simple way of achieving this?

Thanks very much!

2
  • at first filter values that you want then sum them. Commented Aug 6, 2021 at 6:10
  • Please add the code you've tried so far and people here will help you modify it to work properly. Commented Aug 6, 2021 at 6:15

2 Answers 2

1

Please, try the next code:

Sub testSumLimit()
   Dim ws As Worksheet, lastR As Long, sumLimit As Long, rng As Range, i As Long, count As Long
   
   Set ws = ActiveSheet
   lastR = ws.Range("A" & ws.rows.count).End(xlUp).row
   sumLimit = 200: ws.Range("A1").Activate
   For i = 2 To lastR
        count = count + ws.Range("B" & i).value
        If count >= sumLimit Then
            Set rng = ws.Range("A2:B" & i): Exit For
        End If
   Next i
   rng.Select
End Sub
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks FaneDuru! That worked perfectly, very much appreciated!
@Kelvin C Glad I could help! But, don't you need doing something with the respective range? Only selecting it? Basically, selecting ranges or activating sheets is a bad habit, which only consumes Excel resources...
0

It makes no sense to loop until the sum is smaller than 200, because that will make your loop stop already at the first step.

In order to achieve what you want, you need to loop until the sum is larger than 200, and then subtract the last entry.

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.