VBA to sum variable range of data

Jl23

New Member
Joined
Feb 9, 2023
Messages
8
Office Version
  1. 365
Platform
  1. Windows
I am trying to write a code that will sum varying ranges of data. I have it so close but am getting stuck on one thing. I need the code to put the formula in the last cell with a value vs the first blank cell.
Here is the code I'm using and attached is an example of the data I'm working with. I'm new to VBA so I'm likely missing something very obvious, at least I hope so :)

Sub SumF()
Dim y As Variant
Dim firstRow As Variant
Dim lastRow As Variant
lastRow = Range("F" & Rows.Count).End(xlUp).Row
firstRow = Cells(lastRow, 6).End(xlUp).Row
If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then
Cells(lastRow + 1, 6).Formula = "=SUM(F" & firstRow & ":F" & lastRow & ")"
End If
For y = firstRow To 6 Step -1
lastRow = Cells(y, 6).End(xlUp).Row
firstRow = Cells(lastRow, 6).End(xlUp).Row
If firstRow < 1 Then firstRow = 1
If IsNumeric(Cells(lastRow + 1, 1)) And IsEmpty(Cells(lastRow + 1, 2)) Then
Cells(lastRow + 1, 6).Formula = "=SUM(F" & firstRow & ":F" & lastRow & ")"
End If
y = firstRow
If firstRow = 6 Then Exit Sub
Next y
End Sub
 

Attachments

  • Screenshot 2023-04-14 140545.png
    Screenshot 2023-04-14 140545.png
    23.6 KB · Views: 11

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).

Forum statistics

Threads
1,213,535
Messages
6,114,198
Members
448,554
Latest member
Gleisner2

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top