Creating an absolute, yet variable, reference in VBA - vba

First time poster here, I've been searching for the last hour without success so I'm turning to asking for help... My limited VBA knowledge might be a factor here.
I'm creating a quick macro that will sum values cumulatively. I regularly use =SUM($A$2:A2) and AutoFill down to get a cumulative sum. While I can be very quick at doing this, I have to do it several times per day in various sheets. My goal was to have the absolute $A$2 reference to be variable based on the current selected cell.
So let's assume I am trying to add this formula to cell B2. I know I can do:
ActiveCell.FormulaR1C1 = "=SUM(R2C1:RC[-1])"
However, this formula is unusable if my starting cell is anything but B2 and I am trying to cumulatively sum data in various columns.
Is it possible to have VBA count the number of columns between the selected cell and A2 and use this as a variable to set the absolute reference? Such as:
ActiveCell.FormulaR1C1 = "=SUM(R2Cvar:RC[-1])"
where var is =COUNTA(R2C1:ActiveCell)+COUNTBLANK(R2C1:ActiveCell)-1
I know the above code isn't valid, but it's the only way I can think of explaining what I'm trying to achieve.

You'll have to concatenate your formula eg
ActiveCell.FormulaR1C1 = "=SUM(R2C" & var & ":RC[-1])"
But to get your variable you can do
var = (ActiveCell.Column - 1)

Something like:
Sub ytrewq()
Dim s As String
With ActiveCell
s = .Offset(0, -1).Address(0, 0)
.Formula = "=SUM($A$2:" & s & ")"
End With
End Sub
The Offset() generates the address of the cell "just to the left".

Related

VBA creating formulas referencing a range

After several hours of research, I still can't solve what seems to be a pretty simple issue. I'm new to VBA, so I will be as specific as possible in my question.
I'm working with a DDE link to get stock quotes. I have managed to work out most of the table, but I need a VBA to create a finished formula (i.e., without cell referencing) in order to the DDE link to work properly.
My first code is as follows:
Sub Create_Formulas()
Range("J1").Formula = "=Trade|Strike!" & Range("A1").Value
End Sub
Where J2 is the blank cell and A2 contains the stock ticker. It works fine, but when I try to fill out the rows 2 and bellow, it still uses A1 as a static value.
Sub Create_Formulas()
Dim test As Variant
ticker = Range("A1").Value
'Test to make variable change with each row
'Range("J1:J35").Formula = "=Trade|Strike!" & Range("A1:A35").Value
'not working
Range("J1:J35").Formula = "=Trade|Strike!" & ticker
'not working
End Sub
I couldn't find a way to solve that, and now I'm out of search queries to use, so I'm only opening a new topic after running out of ways to sort it by myself. Sorry if it is too simple.
You are referencing absolute cell adresses here. Like you would do when using $A$1 in a normal excel formula.
What you want to do is:
Dim row as Integer
For row = 1 to 35
Cells(row,10).Formula = "=Trade|Strike!" & Cells(row,1).Value
Next row
This will fill the range J1 to J35 with the formula. Since (row,10) indicates the intersection of row and column 10 (J)
Firstly, in your second set of code, you define a variable "test", but never give it a value.
You assign a value to the variable "ticker", and then never reference it.
Secondly, the value you have assigned to ticker is a static value, and will not change when it is entered in a different row.
Thirdly, I think your issue could be solved with a formula in Excel rather than VBA.
The "INDIRECT" function can be quite useful in situations like this.
Try inserting the formula
=INDIRECT("'Trade|Strike'!"&A1)
into cell A1, then copy down.
Note the ' ' marks around "Trade|Strike". This is Excels syntax for referencing other sheets.

sumifs to loop all sheets

I have been searching different forums and cant seem to find my answer.
I have rather basic VBA knowledge and build most of my code from bits online!
Regardless of cell references as I would be able to work these out at a later date.
Please can you let me how I would make a sumifs formula reference across multiple sheets.
This is being build into a template and there would be a different number of sheets with different names each time it is run so I would be not be able to reference the sheets.
sorry thats a bit vague
thanks in advanced
Thanks, so for anyone else who needs this, this is how it was done in full
my original formula was
"=SUMPRODUCT(SUMIF(INDIRECT(" '"&Invoices&"'!"&"A2006:A3005"),A3,INDIRECT("'"&Invoices&"'!"&"B2006:B3005")))"
this worked when putting straight into a cell but as you can see, when adding it to VBA it reads it as a comment. To fix this, every time you use a " you need to add extra " as shown bellow (apart form before the" = at the start and after the )" at the end of the formula)
*****'list all the sheet names in cell AI1 of the sheet summary*****
For i = 1 To Sheets.Count
Sheets("Summary").Range("AI1")(i, 1).Value = Sheets(i).Name
Next i
***'clear the first 3 entries in AI as i didnt need the first three sheet names***
Sheets("Summary").Select
Sheets("Summary").Range("AI1:AI3").Clear
***'select the first sheet name, which is in AI4 as we cleard the first 3 to the last used cell, e.g Ctrl.Shift.down***
Sheets("Summary").Activate
Sheets("summary").Range(ActiveSheet.Range("AI4"), ActiveSheet.Range("AI4").End(xlDown)).Select
***' Name the range invoices***
Selection.Name = "Invoices"
' ***Formula to do a sumIf looping all the shets in the named range Invoices***
Sheets("summary").Range("B3").Formula = "=SUMPRODUCT(SUMIF(INDIRECT(""'""&Invoices&""'!$A$2006:$A$3005""),$A3,INDIRECT(""'""&Invoices&""'!B$2006:B$3005"")))"

Declaring last row references in Excel formulas through VBA

In an attempt to take one of my rudimentary programs, and develop it more I am in need of help referencing last row references in Excel formulas as well as dragging formulas down consistently to the last row of a document.
To elaborate I am attempting to reference the last row in an ever expanding mapping table in my vlookup formula. The reason I need this is because as this mapping table expands when I am no longer coding this program, I need my vlookup formula which will be generated every time I run the program to adapt to the ever changing size.
Also my more pressing issue is in regard to taking that vlookup formula and being able to drag it down to the last row of a worksheet. The worksheet will be static and the last row will range anywhere from 70,000 rows to 90,000 rows. I am trying to avoid loops in this scenario as this will already be a very demanding formula and I would hate to loop through each row.
Currently my rudimentary code looks like this (this was built as a proof of concept, I understand the current method isn't the most ingenious but it served its initial purpose).
Ath.Cells(1, x) = "Business"
Ath.Cells(2, x).Select
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[1],Mapping!R2C4:R264C5,2,0),VLOOKUP(LEFT(RC[1],2),Mapping!R1C3:R264C5,3,0))"
Ath.Range("d2").Copy
Range("d2:d90000").Select
ActiveSheet.Paste
Calculate
I namely want to change this
Ath.Range("d2").Copy
Range("d2:d90000").Select
ActiveSheet.Paste
and
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[1],Mapping!R2C4:R264C5,2,0),VLOOKUP(LEFT(RC[1],2),Mapping!R1C3:R264C5,3,0))"
Perhaps these?
Ath.Range("d2").Copy
Range("d2:d" & Range("D" & Rows.Count).End(xlUp).Row).Paste
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[1],Mapping!R2C4:R" & Sheets("Mapping").Range(ActiveCell.Offset(Rows.Count, -1)).End(xlUp).Row & "C5,2,0),VLOOKUP(LEFT(RC[1],2),Mapping!R1C3:R" & Sheets("Mapping").Range(ActiveCell.Offset(Rows.Count, -1)).End(xlUp).Row & "C5,3,0))"
Combining Dans answer with work of my own I have developed a solution.
Sub Formulas()
Dim Map As Worksheet
Dim Ath As Worksheet
Dim last As Long
Set Ath = Sheets("Athena IBT TEST")
Set Map = Sheets("Mapping")
last = Map.Cells(Rows.Count, "D").End(xlUp).Row
ActiveCell.FormulaR1C1 = "=IFERROR(VLOOKUP(RC[1],Mapping!R1C1:R" & last & "C4,4,0),IFERROR(VLOOKUP(LEFT(RC[1],3),Mapping!R1C2:R" & last & "C4,3,0),VLOOKUP(LEFT(RC[1],3),Mapping!R1C3:R" & last & "C4,2,0)))"
End Sub

VBA to insert and increment formulae in cell

I have this VBA
Sub ApplyCV()
Range("H2:H5000").Formula = "=GetPattern($A2)"
End Sub
Which basically applies the custom function "=GetPattern" to execute the macro of the same name. This works fine.
However, instead of explicitly stating the range (which will vary with each dataset) I'd like to increment the formula on a loop UNTIL the last row of data or until there is no cell value in A:whatever.
Any help with this would be gratefully received.
Many thanks
Try finding the last value in column A (looking from the bottom up) and using that cell's row to define the extent of the range in column H that the formula is applied to.
Range("H2:H" & cells(rows.count, 1).end(xlup).row).Formula = "=GetPattern($A2)"

Formula to remain after running macro

I was wondering how I can have a formula stay on column J2:J600. The formula is =R2 and would go all the way down to =R600. I thought I could manually put the formula in but every time I run my macro, the formulas disappear. Is there a way to embed the formula into the column? Thanks.
EDIT
Sub FormatCounsel()
Sheet2.Range("J2").FormulaR1C1 = "=RC[0]"`
Sheet2.Range("J2").AutoFill Destination:=Range("J2:J600"), Type:=xlFillDefault
End Sub
This is what I put in and I'm getting an error.
EDIT 2
Sorry I just realized that I want the formula =R2 in cells J2:J600. Sorry if I caused any confusion.
I see a big red flag in your code: you're using circular referencing! This means that you're saying J2 = J2. In other words, your formula refers to itself for a value, so it calculates to find the value, but to find the value it needs to calculate, etc...
Entering circular referencing should always give you an error when you manually enter circular referencing. However, when using VBA to enter the CR, I was only able to raise an error by setting Application.Calculation to xlCalculationManual, and then calculating the sheet.
You may have just made a typo, and that explains why there's circular referencing in your code, but I figured I'd explain it anyway. :)
R1C1 formulas use relative references to refer to cells. So when you say RC[0], you're saying that you want to use the cell in the same row and the same column. Let's see some examples. In our example, the formula will be in B2.
Dim r As Range
Set r = Range("B2")
r = "=RC" '<~~~ the equivalent to what you used in your code. Refers to B2.
r = "=R[-1]C" '<~~~ Refers to B1 (current row minus 1).
r = "=RC[1]" '<~~~ Refers to C2 (current column plus 1).
r = "=R[1]C[1]" '<~~~ Refers to C3 (current row and current column plus 1).
r = "=R[-1]C[-1]" '<~~~ Refers to A1 (current row and current column minus 1).
Now, as far as entering formulas into cells, it can be done all at once and very easily. Consider the example below:
Sub FormatCounsel()
Sheet2.Range("J2:J600") = "=RC[1]" '<~~ Each cell will refer to the cell to the right.
End Sub
Any time you write something else to those cells or clear them with the macro, you will lose those formulas. You need to find the place in your code where you are overwriting or clearing them, and modify that code. The other option is writing those formulas back to the cells at the end of the macro. You can accomplish this with:
Range("J2").FormulaR1C1 = "=RC[0]"
Range("J2").AutoFill Destination:=Range("J2:J600"), Type:=xlFillDefault