Excel VBA - Sum function - vba

I'm trying to calculate the sum of my columns (column I). From 1 to the last record in I it has. When I record a macro I get this as output, but this is gibberish to me.
ActiveCell.FormulaR1C1 = "=SUM(R[-11]C:R[-4]C)"
I found another topic and there they said
LastRow = .Range("I" & .rows.Count).End(xlUp).row
Range("I"&LastRow) = "SUM(I1:I...)"
Except in my case, I can't figure how to enter the lastrow of I in it.
All help is welcome :)

There are two ways of referencing a cell - 'R1C1' and 'A1'. The former works like co-ordinates, with a relative number of rows (R) and cells (C).
The other reference style refers to the cell name on the sheet - B6, F67 etc.
Let's say you want to put your Sum() in cell B1 and LastRow has a value of 6:
ActiveSheet.Range("B1") = "=Sum(I1:I" & LastRow & ")"
Would insert the following function in cell B1:
=SUM(I1:I6)

Related

Simplifying complex excel formula with VBA

I have a macro that is generally slow due to overuse of LOOKUP formulas. I want to insert some VBA variables to speed these up. I am currently working on speeding up the formula below:in Excel:
=IF(ISNA(MATCH(A2,Summary!B:B,0)),"n",I2-((I2/LOOKUP(2,1/(I:I<>""),I:I))*VLOOKUP(A2,Summary!$G$10:$H$902,2,FALSE)))
in VBA:
"=IF(ISNA(MATCH(RC[-9],Summary!C[-8],0)),""n"",RC[-1]-((RC[-1]/LOOKUP(2,1/(C[-1]<>""""),C[-1]))*VLOOKUP(RC[-9],Summary!R10C7:R902C8,2,FALSE)))"
The portion I need to replace is LOOKUP(2,1/(C[-1]<>""""),C[-1]). All this does is reference the last non empty cell in column I. Right now I have the following code to return the address of the last cell in VBA
Sub FormulaTest()
Set lRow = Range("I1").SpecialCells(xlCellTypeLastCell).Address
End Sub
I am trying to figure out how to implement this "lRow" into the VBA code for the formula. Can anyone steer me in the right direction?
**EDIT 1
Please see Fernando's comment below. He has the right idea however the solution is still off a bit. Ill try to explain it better in a few comments: First off, The first row is always a title row, the last row is always a sum row, the current tab is the "Sales" tab, and the amount of rows in any given Sales tab will vary (could be I1:I59, could be I:1:I323).
In this example I1 is a row title and I59 is the sum of I2:I58. Rows I2:I58 are dollar amounts. My macro places this formula in J2:J58. This formula takes each row's dollar amount (I2:I58) as a percentage of the total (I59) and multiplies it by an input amount on the Summary tab (the VLOOKUP). This amount is then subtracted proportionately from the dollar value in column I with the J cell showing the result.
I am looking to eliminate the need for the LOOKUP function (selects last non empty cell) within my formula above: LOOKUP(2,1/(C[-1]<>""""),C[-1]).
**EDIT 2
Fernando's solution worked. Thank you all for your input
This would return the last non-empty row in column I
with Worksheets("Summary")
lRow = .Cells(.Rows.Count, "I").End(xlUp).Row
end with
So your code would be
sub testy
dim lRow as long
with Worksheets("Summary")
lRow = .Cells(.Rows.Count, "I").End(xlUp).Row
end with
"=IF(ISNA(MATCH(RC[-9],Summary!C[-8],0)),""n"",RC[-1]-_
((RC[-1]/R"&lRow&"C[-1])*VLOOKUP(RC[-9],Summary!R10C7:R902C8,2,FALSE)))"
In your solution you're using xlCellTypeLastCell. This is very useful, but it calculates based on UsedRange, which may not be what you want. with this, if you have data up to row n and then you update the data and now you have less records, the last row with xlCellTypeLastCell will still be n, so be careful with that.
Assuming that you are doing all your work on the active sheet, looking up to a "Summary" sheet:
Sub fillCol()
Dim aRow As Long, bRow As Long
aRow = Cells(Rows.Count, "I").End(xlUp).Row
bRow = Sheets("Summary").Cells(Rows.Count, "I").End(xlUp).Row
Range("J2:J" & aRow).FormulaR1C1 = "=IF(ISNA(MATCH(RC[-9],Summary!C[-8],0)),""n"",RC[-1]-" _
& "((RC[-1]/" & aRow & ")*VLOOKUP(RC[-9],Summary!R10C7:R" & bRow & "C8,2,FALSE)))"
End Sub
You made need to change the columns which contain the contiguous range (in order to determine the last row)

VBA Subroutine to fill formula down column

I have a current Sub that organizes data certain way for me and even enters a formula within the first row of the worksheet, but I am running into the issue of wanting it to be able to adjust how far down to fill the formula based on an adjacent column's empty/not empty status. For example, each time I run a report, I will get an unpredictable amount of returned records that will fill out rows in column A, however, since I want to extract strings from those returned records into different Columns, I have to enter formulas for each iteration within the next three columns (B, C, and D). Is there a way to insert a line that will evaluate the number of rows in Column A that are not blank, and then fill out the formulas in Columns B, C, and D to that final row? (I know that tables will do this automatically once information is entered in the first row, but for logistical reasons, I cannot use tables).
My current code that fills out the formula in Column B, Row 2 is:
Range("B2").Select
ActiveCell.FormulaR1C1 = "=MID(RC[-1],FIND(""By:"",RC[-1])+3,22)"
Thanks!
The formula that you actually need is
=IF(A2="","",MID(A2,FIND("By:",A2)+3,22))
instead of
=MID(A2,FIND("By:",A2)+3,22) '"=MID(RC[-1],FIND(""By:"",RC[-1])+3,22)"
This checks if there is anything in cell A and then act "accordingly"
Also Excel allows you to enter formula in a range in one go. So if you want the formula to go into cells say, A1:A10, then you can use this
Range("A1:A10").Formula = "=IF(A2="","",MID(A2,FIND("By:",A2)+3,22))"
Now how do we determine that 10? i.e the Last row. Simple
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
'~~> Change the name of the sheet as applicable
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find Last Row in Col A
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B2:B" & lRow).Formula = "=IF(A2="""","""",MID(A2,FIND(""By:"",A2)+3,22))"
End With
End Sub
More About How To Find Last Row
You can use this to populate columns B:D based on Column A
Range("B2:D" & Range("A" & Rows.Count).End(xlUp).Row).Formula = _
"=MID($A2,FIND(""By:"",$A2)+3,22)"

Excel Referencing cell entries for use in formula

I'm not sure exactly what to call what I'm trying to do, so searching it has been tough. Basically I have a table of equations, each row has a different equations/references a different column, but all of them reference the same range of rows. i.e. Eq. A = average(A200:A400), Eq. B = sum(C200:C400), etc...
From file to file the range of rows changes, so what I want to do is be able to do is enter the start and end rows into cells and have them auto populate the equations. If anyone could tell me how to do it just for one cell and not an entire table, I could figure it out from there.
Thanks!
Sounds like the INDIRECT function would accomplish this. It allows you to enter in text to be interpreted as a cell reference.
For instance, lets say you wanted the range to cover A200:A400 for a given sheet, and you wanted that desginated in cell A1 of that sheet. In cell A1 you would just type in "A200:A400" then, in the actual equations, you would have:
=AVERAGE(INDIRECT(A1))
You can obviously split this further down, but thats the concept of it.
You could create a form with a few text boxes. Enter the start and end row. Then your code could go through and enter the formula.
Something like this.
Dim lRow as long
Dim lEnd as long
lRow = val(txtBoxStartRow.text)
lEnd = val(txtBoxEndRow.text)
ws.Range("A" & lEnd + 1).Formula = "=average(A" & lRow & ":A" & lEnd & ")"
ws.Range("C" & lEnd + 1).Formula = "=average(C" & lRow & ":C" & lEnd & ")"
This should do:
=AVERAGE(INDIRECT(ADDRESS($B$1;ROW())):INDIRECT(ADDRESS($B$2;ROW())))
In that code I'm assuming cells B1 and B2 contain the limits (you can replace these references with hard number), to use your example: B1 = 200 and B2 = 400.
If you then place this code in any row, you'd get average("rowNumber"200:"rowNumber"400).
Address() gives you the right range reference
Indirect() makes a range out of it
Then you can wrap it in whatever function you like.

Excel - how to increment formula reference along a row

I have really long strings of text saved in roughly 1000 cells down Column A.
I have created the following formula (some VBA included for FindN), placed in cell B1:
=MID($A1,FindN("978",$A1,1),13)
I can copy this formula down Column B just fine. However, I also want to copy this formula across each row, so for example the formulas for the cells across the row should be as follows:
Cell C1: =MID($A1,FindN("978",$A1,2),13)
Cell D1: =MID($A1,FindN("978",$A1,3),13)
Cell E1: =MID($A1,FindN("978",$A1,4),13)
etc...
If I copy the formula in Cell B1 across the row, it will copy across =MID($A1,FindN("978",$A1,1),13) - but I need the "1" to increment by 1 each time.
I think I'd need to adjust the formula slightly, but a bit lost on how to do this...
Any help would be greatly appreciated. Please let me know if I should clarify further.
Use COLUMN() - it gives the column number of the current cell. You can offset this as required.
In this case for your incrementing number use COLUMN() - 1, so that in B you have 1, C; 2 etc.
You need use CELL formula to get current column number. Try something like this:
=MID($A1,FindN("978",$A1,CELL("column";A1)+1),13)
I dont have English Excel and im not sure first argument in CELL forumla is "column"
Try this :
Sub Fill()
With Sheets("Sheet1")
For i = 1 To .Cells(Rows.Count, "A").End(xlUp).Row
.Cells(i, 1).FormulaR1C1 = "=MID($A1,FindN(" & _
Chr(34) & "978" & Chr(34) & _
",$A1," & i - 1 & "),13)"
Next i
End With
End Sub

How to autofill formula for known number of columns but variable number of rows in excel macro

I writing a macro within which I need to autofill some rows with formulas, across multiple columns.
The number of columns is fixed, but each time the macro runs, the number of rows is variable. I use the "record macro" function and the current macro only ever fills my rows to row 16. Below is the code:
Range("D3:P3").Select
Selection.AutoFill Destination:=Range("D3:P16")
I obviously need to change the "P16" to something dynamic.
I have tried to use the following:
Dim LR As Long
LR = Range("D3:P3" & Rows.Count).End(xlUp).Row
Range("B3:P3").AutoFill Destination:=Range("B3:P" & LR)
I am unsure whether the "Dim LR as Long" has to be placed at the very beginning of my macro - or can it just be placed anywhere?
I am getting an error anyway with what i attempted above giving me an "autofill selectio error" (sorry i cant remember the exact error message.
Would someone be able to point me in the right direction?
LR can be declared anywhere before where you first use it, but it's best to do it at the beginning. Your range for LR is incorrect.
LR = Range("D3:P3" & Rows.Count).End(xlUp).Row
Should be
LR = Range("D3:P3").End(xlUp).Row
You should use xlDown if you are trying to find the end of a range BELOW D3:P3
LR = Range("D3:P3").End(xlDown).Row
Would give you the last row with data in all columns D:P in it below D3:P3
I think you're looking for this:
LR = Range("D3:P" & Rows.Count).End(xlUp).Row
but note that this finds the last row with any content in Column D - if there are later rows with content in Cols E-P but not in Col D then those rows will be ignored.
So I used the information provided to me and managed to get the following:
Dim LR As Long
LR = Range("C3:P" & Rows.Count).End(xlDown).Row
Range("D3:P3").AutoFill Destination:=Range("D3:P" & LR)
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$D$2:P" & LR), , xlYes).Name = _
"Table10"
This allowed me to count the number of rows that had already been populated in column "C", and then take the formulas that already existed in cells D3:P3 and autofill them down through the range until the last populated row of column C.
I then used that structure to make the whole range a table, in this case named "Table10".
Great stuff guys - your help allowed me to get exactly what I wanted. Thanks