2

enter image description here

I want a code to sum the Variable rows up if certain condition is met. e.g. If A12 is numeric and B12 is empty then insert a fomula in cell C12 to sum C3:C11. Then perform the same action at C22 and C30. The problem I have is don't know how to define the starting row.

Sub Test()
Dim y As Variant
Dim r As Variant
Dim StartRow As Variant

   LastRow = Range("C" & Rows.Count).End(xlUp).Row
        For y = 3 To 500
            For r = 1 To LastRow

            If InStr(1, Cells(r, 1), "Amount") Then
                StartRow = r

            If IsNumeric(Cells(y, 1)) And IsEmpty(Cells(y, 2)) Then
            Cells(y, 3).Formula = "=SUM(C" & StartRow + 1 & ":C" & y - 1 & ")"
            End If
         End If
      Next r
  Next y

End Sub
2
  • You could do this with just an extra column and without needing VBA... Commented Jun 18, 2015 at 14:13
  • @LS_dev Since this is just a part of my whole code, so I want the VBA code to perform this, could you please help? ^ ^ Commented Jun 18, 2015 at 14:15

1 Answer 1

4
Sub Test()
Dim y As Variant
Dim firstRow As Variant
Dim lastRow As Variant
lastRow = Range("C" & Rows.Count).End(xlUp).Row
firstRow = Cells(lastRow, 3).End(xlUp).Row
If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then
    Cells(lastRow + 1, 3).Formula = "=SUM(C" & firstRow & ":C" & lastRow & ")"
End If
For y = firstRow To 3 Step -1
    lastRow = Cells(y, 3).End(xlUp).Row
    firstRow = Cells(lastRow, 3).End(xlUp).Row
    If firstRow < 3 Then firstRow = 3
    If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then
        Cells(lastRow + 1, 3).Formula = "=SUM(C" & firstRow & ":C" & lastRow & ")"
    End If
    y = firstRow
    If firstRow = 3 Then Exit Sub
  Next y
End Sub
Sign up to request clarification or add additional context in comments.

6 Comments

Hi Abe, Excellent! It works! But May I know how to insert this condition? If IsNumeric(Cells(y, 1)) And IsEmpty(Cells(y, 2)) Then
Edited the answer to include that. Let me know if it doesn't work. I did not test it.
Hi Abe, this works perfectly! but...Still a question, the formula in C12 becomes SUM(C1:C11), what I want is C3:C11. Which part should I amend?
HaHa, I also changed For y = firstRow To 3 Step -1 from 1 to 3 before, but it does not work, that's why I have to ask you.
There are a few other changes as well. Replace you code with this and see if it works.
|

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.