Using .Formula with variable in cells object - vba

I've tried a variety of concats and uses of "" but I cant get .formula to work in the following code. The macro runs without error but it does not populate my sheet. I feel like this: Excel VBA formula with variables is what I am going for but main_row does not appear to be getting assigned to the variable when it is inside the .formula.
main_row = main.Range("b6").Row
calc_col = main.Range("k6").Column
main.Cells(main_row, calc_col).Formula = " = j & main_row / i & main_row "
Is it possible to use .formula with cells object?
Would rather not use application.worksheetfunction because i want end user to see the formula
Anyone have a good source to explain the proper way to qualify variables within .formula?

Try the below, I believe you were nearly there, but you inserting an unnecessary space before the equals sign + the quotes were out.
main.Cells(main_row, calc_col).Formula = "= J" & main_row & " / I" & main_row

Related

Excel vba formula string: array formula - how to simulate Ctrl+Shift+Enter press

I have a worksheet with data and some columns which I fill with formulas via vba. The formula I struggle with is an array formula that looks like this:
Workbooks(job_file).Worksheets(1).Cells(h + b, 195).Formula = _
"{=IF(MAX(IF(B2:M2>$FY" & currentRow & ",$B$1:$M$1))=0,0," & _
"MAX(IF(sheet1!B2:M2>$FY" & currentRow & "," & _
"sheet1!$B$1:$M$1)))+1}"
It's supposed to be an array formula, so that's why I put {} there. However, when run it simply display the formula's text in a cell, without calculating it. I have to manually remove the brackets, and then press Ctrl+Shift+Enter myself.
Is there any way to avoid it? I have a great many rows and I can't ctrlshiftenter each.
I tried running it without brackets, it works, but gives a #VALUE! error, which can also be fixed by applying Ctrl+Shift+Enter.
To create an array formula with a simulated ctrl+shift+enter (aka CSE), use the Range.FormulaArray Property instead of the Range.Formula Property and let Excel add the 'curly braces'.
with Workbooks(job_file).Worksheets(1)
.Cells(h + b, 195).FormulaArray = _
"=IF(MAX(IF(B2:M2>$FY" & currentRow & ",$B$1:$M$1))=0,0," & _
"MAX(IF(sheet1!B2:M2>$FY" & currentRow & ", sheet1!$B$1:$M$1)))+1"
end with
I noticed in your formula that you use B2:M2 and sheet1!B2:M2. Shouldn't they both be sheet1!B2:M2?
There are some considerations.
Runtime Error: 1004 - Too long. There is a reduced character limit of 255 for FormulaArray but there are work-arounds.
Runtime Error: 1004 - Broken String. Remember that all quotes within a quoted string must be doubled up. This is easily one of the most common causes of errors when trying to write a formula into a cell through VBA. Hint: TEXT(,) can be used instead of "" so you don't have to type """" for a zero-length string.
FormulaArray accepts both xlR1C1 and xlA1 style formulas. If you can wrap your head around xlR1C1 style formula syntax, it is generally easier to construct a concatenated formula string in xlR1C1 since you can use digits to represent column numbers instead of trying to convert column ordinals to a column letter. However, do not try to mix-and-match xlA1 and xlR1C1 range references in the same formula; they must all be one style or the other.
If you are having trouble formulating a string that will be accepted as a formula, put a tick (e.g. ' ) in front of the first equals sign then run the code and return to the worksheet to see what was put in. Make modifications on the worksheet until you have a working formula then transfer those modifications to the VBA code.
As a note, it looks like this can be done without an array formula, like so:
Workbooks(job_file).Worksheets(1).Cells(h + b, 195).Formula = _
"=IF($FY" & currentRow & ">MAX(B2:M2),0," & _
"MAX(INDEX((B2:M2>$FY" & currentRow & ")*$B$1:$M$1,)))+1"

How to use quotes within a formula along with Active cell formula

So I am trying to go for dynamic sheet referencing and this is the code I have so far:
Application.Range(strNewCell2).Activate
ActiveCell.Formula = "=SUM(INDIRECT(inputVal& "!H2:H402"))"
Note: inputVal is a variant variable that contains the sheet name
However when I run it, it gives me an unexpected end of statement
error.
The other method that I tried is:
Application.Range(strNewCell2).Activate
ActiveCell.Formula = "=SUM(INDIRECT(inputVal& ""!H2:H402""))"
I tried this after looking up many things, however that isn't the correct way either as it escapes the double quotes but still keeps one set of them within the formula, which gives me the wrong result.
So what I am trying to do is somehow use indirect within the formula statement without getting an error.
Try,
Application.Range(strNewCell2).Activate
ActiveCell.Formula = "=SUM(INDIRECT(""'" & inputVal & "'!H2:H402""))"
However, I'm curious as to why you require INDIRECT at all if you are constructing the worksheet/range reference.
ActiveCell.Formula = "=SUM('" & inputVal & "'!H2:H402)"

VBA: Using VLookUp to Set Dynamic Values in loop?

New VBA user here...
I have set up a Macro that runs for each file in a folder, as a loop.
In one part of the macro, there is an equation that contains a value that differs for each file.
Here is the equation (the value that changes for each file is 0.2483, everything else stays the same):
ActiveCell.FormulaR1C1 = "=(((" & signal_array(Element, 1) & ")-
R[-83]C)/R[-85]C)*1000*0.2483"
I have set up a table that lists each file name and its corresponding value in another workbook. I have attempted to use vLookUp within the equation to find the value based on the file name - the file of which is active.
Here's what I have so far, for which I get a "Run-Time Error: 1004" on:
ActiveCell.FormulaR1C1 = "=(((" & signal_array(Element, 1) & ")-
R[-88]C)/R[-90]C)*1000*(=VLOOKUP(" & ActiveWorkbook.Name & ",'[Calibration
Curves.xlsm]Sample Weights'!A2:B10,2,FALSE))"
Suggestions on how to make this work?
Try getting rid of the = in the formula and also use consistent cell notation (i.e. don't mix A1 notation with R1C1 notation):
ActiveCell.FormulaR1C1 = "=(((" & signal_array(Element, 1) & ")-
R[-88]C)/R[-90]C)*1000*(VLOOKUP(" & ActiveWorkbook.Name & ",'[Calibration
Curves.xlsm]Sample Weights'!R2C1:R10C2,2,FALSE))"

Using a function in place of sheet_name string in vlookup formulas [duplicate]

I'm having trouble with the usage of Indirect function.
Here's what i'm looking for, I'm trying to create a dynamic vlookup based on the current tab.
=VLOOKUP(B3;'NH BBC'!$E$1:$Z$188;MATCH("Share Outstanding";'NH BBC'!$E$1:$Z$1;0);0)
My plan is to modify the 'NH BBC' by 'NH ' & RIGHT(CELL("filename");3) Supposing that the name of my tab is XXX_BBC.
I've tried to use indirect function but I'm not sure I'm on the good way.
Here's what I've tried:
=VLOOKUP(B3;INDIRECT("'" "NH " & "RIGHT(CELL("'" & "filename" & "'" & ");3)" & "!" & "E1:Z188");MATCH("Share Outstanding";'NH BBC'!$E$1:$Z$1;0);0)
Hope I've been clear.
Thanks in advance !
You are trying to concatenate some text with the results returned from a formula, but you are sticking the formulas in quotes, turning them into text. Furthermore, you are not keeping very good track of your text. There are quotes all over the place. Take this bit by bit in a seperate cell if need, slowly growing your formula from the inside out so you can insure everything is as expected. Right now it's a mess.
INDIRECT("'" "NH " & "RIGHT(CELL("'" & "filename" & "'" & ");3)" & "!" & "E1:Z188")
Should be:
INDIRECT("'NH " & RIGHT(CELL("filename");3) & "'!E1:Z188")
No need for all the complication.
I've finally found and this formula is working perfectly.
VLOOKUP($B3;INDIRECT("'NH "&RIGHT(CELL("filename");3)&"'!$G$1:$ZZ$9999");MATCH("SHARE_OUTSTANDING";INDIRECT("'NH "&RIGHT(CELL("filename");3)&"'!$G$1:$ZZ$1");0))
By the way the issue i've got is that the cell are changing when i'm using the formula in another tab. Is this possible to look the value i've obtained ?
Something like a F9 ?

Summing cells from another sheet using offset

I'm trying to get this code to work for summing cells:
Worksheets("Sheet2").Range("C3").Offset(i, j).Formula = "=Sum("
&Worksheets("Sheet1").Range("A3").Offset(2*i,j).Address & ":" &
Worksheets("Sheet1").Range("A7").Offset(2*i,j).Address & ")"
It keeps giving me the right cells but from the wrong sheet. So for the first iteration I get sum(A3:A7) in cell C3 of Sheet2 but the A3:A7 stays referenced to Sheet2 not Sheet1.
Thanks!
You need to specify the name of the sheet in the formula too. Your code will work if you write it like this:
Worksheets("Sheet2").Range("C3").Offset(i, j).Formula = "=Sum(Sheet1!" & _
Worksheets("Sheet1").Range("A3").Offset(2 * i, j).Address & ":" & _
Worksheets("Sheet1").Range("A7").Offset(2 * i, j).Address & ")"
Try this code - it uses the External:=True parameter of .Addressto retrieve the full address. While this also includes the workbook name, Excel will remove this automatically so you end up with Sheet1!A3. Also note that I used the range A3:A7 as source as .Address can handle multi-cell ranges and you don't need to take care of it manually:
Sheets("Sheet2").Range("C3").Offset(i, j).Formula = "=SUM(" & _
Sheets("Sheet1").Range("A3:A7").Offset(2 * i, j).Address(External:=True) & ")"
Be aware that hard coding references such as A3 can lead to bugs in the long run, as the user (or even the developer at some stage) might modify the sheet structure. It is best practice to use named ranges, i.e. create a named range for each cell/range you refer to and then access it in VBA with SheetX.Range("rngStartCell") or similar!