How to have conditional sumif formula throughout a range? - excel

i'm trying to do a sumif of cells in column K to the right whenever there's a cell value in column J = "subtotal". Right now my code isn't working and i'm not sure if it's because i wrote my sumif statement wrong. My range starts at row 13 and the last row varies. My condition to sum is to sum the cells in column K as long as the cells in column B are the same.
Please see below for my code! Would appreciate any help for this...I'm getting an optional error but i'm not 100% sure why.
enter code here
dim startrow as long
dim groupstartrow as long
groupstartrow = 13
with ws.name("sheet 1")
mergelastrow = .Cells(.rows.Count, 2).End(xlUp).Row
'every time a cell in column J says GL total,
'add a formula next to it in column K that sums cells from i from beginning of the range
'as long as i in column b is equal to the b on the same row
'as the cells being summed is my goal
For i = startrow + 1 To mergelastrow + 1
If Cells(i, 10) = "subtotal" Then
Range.Cells(i, 11) = "=SUM(" & Cells(groupstartrow, 11).Address & ":" & Cells(i - 1, 11).Address & ")"
groupstartrow = i + 1
End If
end with
end sub

Related

Add moving average value in last row using array in Excel VBA

'The code should add the moving average to last row using array. The Prices to be use to average are in range "E6:E7555". The values will be written in "G7555". There is an existing moving average values in range "G6:G7554". Need help from Excel VBA expert to correct the codes which I think in step 1 and 2 below.
Options Explicit
Sub Add_MovingAverage_to_LastRows()
Dim maArray As Variant
Dim runSum, ma() As Double
Dim i, lRow, iPeriod, iCol As Long
iPeriod = 7
'set last row and reference range to calculate
With Worksheets("Sheet1")
lRow = .Cells(Rows.Count, 1).End(xlUp).Row 'Row "7555"
maArray = .Range(.Cells(lRow - (iPeriod -1), 5), .Cells(lRow, 5)).Value2 'Column "E"
End With
'set the lower and upper bound
ReDim ma1(lRow - (iPeriod - 1) To lRow, 1 To 1)
'step 1 calculate the SUM for last row, sum (row "7549" to row "7555")
runSum = 0
For i = lRow - (iPeriod-1) To lRow
runSum1 = runSum1 + maArray(i, 1)
Next
'step 2 calculate the AVERAGE for last row, average (row "7549" to row "7555")
ma(1, 1) = runSum / iPeriod
'write the values to worksheet
iCol = 7 'Column "G"
With Worksheets("Sheet1")
.Range(.Cells(lRow, iCol), .Cells(lRow, iCol)).Value2 = ma
End With
Erase maArray: Erase ma
End Sub
I think you may want to stick to a Formula on G column instead of VBA. If you add this formula on G6 and drag down: (Test it out on column H next to it)
=AVERAGE(INDIRECT("E"&IF(ROW()-6<6,6,ROW()-6)&":"&"E"&ROW()))
The IF Statement is to not break the formula on the first few rows of the file.
It will always grab the last 6+current row of values in Column E to calculate the Average.
Edit: Summary
="E"&IF(ROW()-6<6,6,ROW()-6)&":"&"E"&ROW() if you paste this into I6 and drag down you can see how it is just graving the 7 Cell Range you are looking for. When you enclose this into INDIRECT then you can use this inside other formulas as a "literal range" as in my answer above with AVERAGE.
Edit 2: VBA Code to automatically drag/fill down formula.
Sub UpdateFill()
Dim lRow As Long, lFormulaRow
With ThisWorkbook.Sheets("Sheet1")
lDateRow = .Cells(Rows.Count, 1).End(xlUp).Row
lFormulaRow = .Cells(Rows.Count, 7).End(xlUp).Row
If lDateRow > lFormulaRow Then
.Range("G" & lFormulaRow & ":G" & lDateRow).FillDown
End If
End With
End Sub

Insert Row and Copy Row Above with different values

I am trying to write some VBA that does two things:
When a value J column = "XY" duplicate the row by inserting the same data into a row below
In the newly inserted row, change values in G, H & L to "0"
So far, I have found this, which works to insert a blank row but I cannot figure out how to do the rest:
Dim i As Range
Dim cell As Range
Set i = Range("J:J")
For Each cell In i.Cells
If cell.Value = "XY" Then
cell.EntireRow.Copy
cell.Offset(1).EntireRow.Insert
End If
Next
The above inserts a blank row but I also need to copy and paste the row above its values and change some.
When inserting/deleting rows it's usually best to loop from the bottom up.
That's what the following, simple, example does.
Sub InsertXY()
Dim idx As Long
For idx = Range("J" & Rows.Count).End(xlUp).Row To 1 Step -1
If Range("J" & idx).Value = "XY" Then
Rows(idx).Copy
Rows(idx + 1).Insert Shift:=xlDown
Intersect(Rows(idx + 1), Range("G:H, L:L")).Value = 0
End If
Next idx
End Sub
Before
After

subtract between last cell from a column and last cell from another column, and put the result in a specific cell

I need some vba code to subtract between last cell from column B and last cell from column D and put the result in cell N1. The position of last cell, in both columns may variate.
Thx
This code does the trick for you. It takes the last cell of both column B and D and it subtracts their value on the N1 cell:
Sub MySub()
Dim lastBRow As Long
Dim lastDRow As Long
lastBRow = Range("B" & Rows.count).End(xlUp).Row
lastDRow = Range("D" & Rows.count).End(xlUp).Row
Range("N1").Value = Range("B" & lastBRow).Value - Range("D" & lastDRow).Value
End Sub

Excel VBA code for simple formula between cells

I need a code for these orders:
Go to first blanks cell in column C.
Calculate the number in column D minus 14 and do it as long there is a number right to the cell in D (there is blanks in column D)
Copy the result in column C and paste it as values to Column B.
note: I need it to stay in original rows.
OP_wb.Sheets("Optic Main").Activate
Dim FirstRow As Range
Dim LastRow As Range
Set FirstRow = Range("C1").End(xlDown).Offset(1, 0)
Range("E1").End(xlDown).Offset(0, -2).Select
Range(FirstRow, LastRow).FormulaR1C1 = "=(c4-14)"`
try this:
1.
Set FirstRow = Range("C1").End(xlDown).Offset(1, 0)
Set lastrow = Range("E1").End(xlDown).Offset(0, -2)
Range("E1").End(xlDown).Offset(0, -2).Select
2.
Range(FirstRow, lastrow).FormulaR1C1 = "=(c4-14)"
3.
Selection.AutoFill Destination:=ActiveCell.Range("A1:A" & lastrow)
hope this helps

SUM Function in VBA - not hard coding rows and columns

How do I use the lastRow variable in the sum function in vba? After I count the number of words in each row until the last row, I would like to add up the individual totals from each row into an overall total column but I do not want to hard code the range into the sum function in vba? Is there another way?
Example:
Column: A B C D E F
NRow 1: 2 3 4 5 6 7
NRow 2: 3 4 5 6 7 8
Total 3: 5 7 9 11 13 15
Want to avoid SUM(R[-2]C:R[-1]C)? I would like SUM(R[lastRow]C:R[-1]C) or something that would function in the same way.
Thank you!
Something like this which
Sets the usedrange on the active sheet from A1 to the last used cell in column F
Goes to the first cell below this range Cells(rng1.Cells(1).Row + rng1.Rows.Count, 1), resizes to the amount of columns in the range of interest (6 in this case)
Enters the forumula "=SUM(R[-" & rng1.Rows.Count & "]C:R[-1]C)" where rng1.Rows.Count gives the first row dynamically
code
Sub GetRange()
Dim rng1 As Range
Set rng1 = Range([a1], Cells(Rows.Count, "F").End(xlUp))
Cells(rng1.Cells(1).Row + rng1.Rows.Count, 1).Resize(1, rng1.Columns.Count).Value = "=SUM(R[-" & rng1.Rows.Count & "]C:R[-1]C)"
End Sub
If you can guarantee that there is always data in column A then to find the last row you could do the following:
Option Explicit
Sub addSums()
Dim lstRow As Integer
With Excel.ThisWorkbook.Sheets("Sheet1")
lstRow = .Cells(.Rows.Count, 1).End(Excel.xlUp).Row
Dim j As Integer
For j = 1 To .Cells(1, .Columns.Count).End(Excel.xlToLeft).Column
.Cells(lstRow + 1, j) = "=SUM(R[-" & lstRow - 1 & "]C:R[-1]C)"
.Cells(lstRow + 1, j).Font.Bold = True
Next j
End With
End Sub
Seems to work ok on the following:
If your source data is coming frm an external source, the appropriate mechanism is:
Create a Named Data Range around the input table;
Set the inut table to automatically resize on refresh; and
Then use the Named Data Range in your functions.

Resources