VBA script to insert INDEX/MATCH formula with dynamic reference/arrays - vba

I'm looking to simply insert an INDEX/MATCH formula in the column next to an existing selection (this will be part of a larger Sub). The reference/look-up array in the formula needs to be dynamic.
So far I've managed to successfully insert the formula. However, the reference/lookup-arrays have been manually input by me as I know the current Range (which is likely to change):
Selection.Offset(0, 1) = "=INDEX($J$3:$J$31,MATCH(INDIRECT(""RC[-2]"",0),$H$3:$H$31,0))"
How can I amend the $J$3:$J$31 and the $H$3:$H$31 to update dynamically? I've had success separately with something like 'Range("J3", Range("J3").End(xlDown))', but I can't seem to work it into the code above.

You can integrate variables into the formula, it becomes a bit tricky, and I imagine there are better ways to accomplish this, but it's the method I use when I need dynamic ranges in formulas in VBA. I'll provide an example below that should help:
I'm assuming the J3 and H3 will remain the same, but the end of the range is what you expect to change. If this is not the case, let me know.
You're essentially replacing the "31" in your range reference with " & [variable] & " (quotes included).
EDIT: I use Sheet1 as an example for the row count; so just update that to whatever the applicable sheet & range would be.
Dim rCount As Long
rCount = Sheet1.Range("A" & Rows.Count).End(xlUp).Row
Selection.Offset(0, 1) = "=INDEX($J$3:$J$" & rCount & ",MATCH(INDIRECT(""RC[-2]"",0),$H$3:$H$" & rCount & ",0))"

Related

Writing a formula with concatenated parts into a cell

Scenario: I have a code that should write a formula to a worksheet cells. This formula is for an API to retrieve some value. My formula is inside a loop (this is done for multiple columns) and references the first row for an identifier.
The original formula:
=FS(B1;"FI(DATE,,DATE)")
The modified formula with the floating reference (inside the loop):
For i = 1 To lColumn
If wb.Worksheets("Dates").Cells(i, 1).Value <> "" Then
wb.Worksheets("Dates").Cells(i,2).value = "=FS(" & i & "1;"FI(DATE,,DATE)")"
End If
Next i
Where lColumn is some pre-defined number.
Issue: I keep getting the "Unexpected end of statement" error in the formula part of the loop.
What I already tried: I tried different variations, repositioning the "s and 's, for example:
wb.Worksheets("Dates").Cells(i,2).value = "'"=FS(" & i & "1;"FI(DATE,,DATE)")""
or
wb.Worksheets("Dates").Cells(i,2).value = "'=FS(" & i & "1;"FI(DATE,,DATE)")"
or
wb.Worksheets("Dates").Cells(i,2).value = "'""=FS(" & i & "1;"FI(DATE,,DATE)")"
and so on. But the error still persists.
Question: What is the proper way to do this operation?
Working with formulas in VBA is a little bit tricky:
To write a formula, use the range.formula property, not the .value.
You have to write the formula as if you are using an english Excel. Parameter-separator is comma (not semicolon).
If a formula needs a quote, double it so that the VBA compiler understands that you want a quote within a string.
I find it helpfull to write a formula into a variable before assigning it - you can check in the debugger if it is exactly how it should before assigning it.
To check how the formula should look like, write it into a cell, change to the VBA-editor, open the immediate window and write ? activecell.formula
Try (untested as the formula you need is not valid to us):
with wb.Worksheets("Dates")
dim f as string, adr as string
adr = cells(i, 1).address(false, false) ' get rid of Dollar signs
f = "=FS(" & adr & ",""FI(DATE,,DATE)"")"
.Cells(i, 2).formula = f
end with
wb.Worksheets("Dates").Cells(i,2).formula = "=FS(" & Cells(1, i).Address(0,0) & ";""FI(DATE,,DATE)"")"
There may be a better way to convert the column number to a letter (which is the problem you are having, along with the double quotes)!

Using relative/abs references to insert a function using VBA

I have some formulas I am attempting to insert into my worksheet through the use of VBA. The rows are dynamic. Whether I attempt to insert the formula with a standard formula or R1C1, part of the formula changes the relative references where I need but not on another.
Range("B25:B" & LastRow).Formula =
"=IFERROR(IF(ISTEXT(E$21),AVERAGEIF(BottomLeftTable[Billing
Name],$A25,BottomLeftTable[Margin]),""""),"""")"
This causes the istext portion to evaluate only E21 when it should be E21 in B25, F21 in B26, G21 in B27, etc. What I find weird is the inserted formula will actually change the $A25 as needed. It places A25 in B25, A26 in B26, A27 in B26, etc.
From what I've read, VBA does not allow R1C1 functions to change the reference so ultimately my question is can the standard insert formula work to paste the formulas where I need them while changing the reference as the formula fills down rows and if so, how to go about doing so? Thank you!
FWIW, here is a loop that would individually set the formula in each cell:
Dim r As Long
For r = 25 To lastRow
Cells(r, "B").Formula = "=IFERROR(IF(ISTEXT(" & Cells(21, r - 20).Address & _
"),AVERAGEIF(BottomLeftTable[Billing Name],$A" & r & _
",BottomLeftTable[Margin]),""""),"""")"
Next r

How to set a variable counter based on a non specific cell in VBA?

I basically want to set a macro that, when run, will select a range of data to create a chart. The amount of columns in the data is set at 2, but the amount of rows will change as more data is added. I was thinking of doing something along the lines of:
Sheets("Risk ranking").Range("C2:D" & counter & ").select
And then using that selection to create the graph (the syntax may be off for that selection... still not too good at know where to place " and & in this kind of scenario... please provide a fix to that as well if it is wrong). The thing is, I need the counter to be an integer equaling the difference between the second row and one less than the first empty ("") cell when going down the rows. How do I set this up?
Try this:
With Sheets("Risk ranking")
.Range("C2:D" & .Range("C" & Rows.Count).End(xlup).Row).Select
End With
This will always size your range to go to the farthest down non-empty row in column "C".
To set chart range:
With Sheets("Risk ranking")
Charts(1).SetSourceData Source:= .Range("C2:D" & .Range("C" & Rows.Count).End(xlup).Row)
End With

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.

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