Insert formula that contains dynamic cell reference using VBA - vba

I need to be able to pass a dynamic cell reference into a formula in a cell and need to use VBA to do it.
i = 2
If I need to reference B2 I'd do the following:
formula = "= "B" & i"
But that doesn't work.
How do I do this?
Thanks.
Edit:
Sheets(v).Range("K" & 2).Formula = "=networkdays(b" & i & ", today())"
That's my code

You don't need to quote "B":
.Formula = "=B" & i
There are other ways, such as:
.Formula = "=" & Cells(i, "B").Address(False, False)
The OP changed the question:
.formula = "=networkdays(b" & I & ",today())"

Related

VBA -- variable in .formula

is there a more elegant (simpler) way to put a variable in .formula? I don't want to use .formulaR1C1
I have this code:
Range("C8").Select
Selection.End(xlDown).Select
PosR = ActiveCell.Row
KonR = PosR - 2
Range("N" & PosR).Select
aAddress = Range("$N$9").Address & ":" & Range("$N$" & KonR).Address
ActiveCell.Formula = "=SUM(" & aAddress & ")"
Obviously I want to put =SUM($N$9:$N$101) (101 is the last cell minus 2) into that cell and this code does the job. But I just want to be sure that this is the easiest way to do this.
The easiest way is to skip all that selecting and those variables
PosR = Range("C8").End(xlDown).Row
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
Edit: to be more explicit, the easiest way is to use FormulaR1C1 but you said you didn't want to, so...
You can use the code below (without using Select and ActiveCell:
PosR = Range("C8").End(xlDown).Row
KonR = PosR - 2
Range("N" & PosR).Formula = "=SUM(" & Range("$N$9").Address & ":" & Range("$N$" & KonR).Address & ")"
Or, the much simplier version:
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & KonR & ")"
Well you should be trying to avoid using Select in VBA. You've made the actual inclusion of a variable in the .Formula about a simple as it gets, but your whole code could be simplified:
PosR = Range("C8").End(xlDown).Row
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
Really you should be fully qualifying your ranges too, like so
With ThisWorkbook.Sheets("Sheet1")
PosR = .Range("C8").End(xlDown).Row
.Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
End With
And if you have blank cells in column C then your use of xlDown will fail to find the last cell. You may want to look at ways of finding the last cell in VBA or simply use
' Again, preferably fully qualified
Range("C" & Rows.Count).End(xlUp).Row
Range("$N$9").Address gives exactly "$N$9".
Range("N9").Address gives the same. Thus, it is a bit overwork. Check out the first two debug.print in the sample below.
Thus, once you calculate the last row and assign value to it lngLast, it is possible to get the formula like this:
"=SUM(N9:N" & lngLast & ")"
Option Explicit
Public Sub TestMe()
Dim strA As String
Dim lngLast As Long
strA = Range("$N$9").Address
Debug.Print strA = "$N$9"
strA = Range("N9").Address
Debug.Print strA = "$N$9"
lngLast = Range("N" & Rows.Count).End(xlUp).Row - 2
ActiveCell.Formula = "=SUM(N9:N" & lngLast & ")"
End Sub
Good morning, everyone :)

Insert formula with reference to active cell row

I am trying to insert a formula into a cell and trying to use a dynamic cell reference by using ActiveCell.Row.
Range("Q" & ActiveCell.Row).Formula = "=IF(Range(""P"" & ActiveCell.Row).Address ="""",""DD/MM/YYY"",CONCATENATE(NETWORKDAYS(O21,P21),"" Working Days""))"
But I am getting an application defined error.
Please can someone show me where I am going wrong? Thanks
Range("Q" & ActiveCell.Row).Formula = "=IF(" & Range("P" & ActiveCell.Row).Address & " ="""",""DD/MM/YYY"",CONCATENATE(NETWORKDAYS(O21,P21),"" Working Days""))"
You have to comment out the VBA code in the string.

VBA: Cell designations not being evaluated

I have the following code in VB:
ActiveCell.Formula = " = COMPANYNAME " & " & " & "R[-12]C[-3]" & " & " & "VLOOKUP(RC[-6],R3C7:R22C18,9)"
I want to get a cell that has in it: = COMPANYNAME & D25 & VLOOKUP(A26,$G$3:$R$22,9)
Instead, I get a cell with = COMPANYNAME & R[-12]C[-3] & VLOOKUP(RC[-6],R3C7:R22C18,9)"
Basically, the cell designations are not being evaluated.
What am I doing wrong?
Change ActiveCell.Formula to ActiveCell.FormulaR1C1
By using ".Formula", it expects cells to be referenced in "A1" fashion, and therefore doesn't know how to compute the R/C references, and appears to see the whole thing as just a string instead of a formula (also you may need to remove the spaces from between the &'s).

Excel VBA hlookup function

I am trying to use the excel VBA HLookup function. I have tried it two ways and both produce error. Could anyone explain me what is that I am doing wrong?
First try:
lookupValue = Worksheets(1).Name & "!A1"
tableArray = Worksheets(3).Name & "!$A$1:$" & Col_letter & "$1"
Worksheets("Comparison").Cells(1, 2).Value = "=HLookup(" & lookupValue _
& ";" & tableArray & ";1;FALSE)"
Second try:
tda = Worksheets(1).Cells(1, 1).Value ' I also tried using tda without .Value
Table = Worksheets(3).Range(Cells(1, 1))
Worksheets("Comparison").Cells(1, 2).Value = WorksheetFunction. _
HLookup(tda, Table, 1, False)
For your first one, you need to use US regional settings, so a comma separator, and you should really enclose the sheet names in single quotes in case they contain spaces or look like special names (e.g. dates):
lookupValue = "'" & Worksheets(1).Name & "'!A1"
tableArray = "'" & Worksheets(3).Name & "'!$A$1:$" & Col_letter & "$1"
Worksheets("Comparison").Cells(1, 2).Formula = "=HLookup(" & lookupValue _
& "," & tableArray & ",1,FALSE)"
and for the second you have to use a range object for the table argument:
tda = Worksheets(1).Cells(1, 1).Value ' I also tried using tda without .Value
Set Table = Worksheets(3).Range(Worksheets(3).Cells(1, 1), Worksheets(3).Cells(1, Col_letter))
Worksheets("Comparison").Cells(1, 2).Value = WorksheetFunction. _
HLookup(tda, Table, 1, False)
I have assumed Table is declared as Variant, Object or Range.
Note you will still get a run-time error if there is no match for your lookup value.
what you're doing there usually works, which is creating a string with the function you want to call and inputting it.
I don't think that's the safest way, since it would not work if you run that macro from an Excel with a different language.
the proper way to call an Excel function from VBA call is for example:
cells(1,2) = Application.WorksheetFunction.VLookup(123,Range("A1:C100"),3,FALSE)
anyway if you'd rather use this string approach the problem in the first try is that
"=HLookup(" & lookupValue _
& ";" & tableArray & ";1;FALSE)"
results in the string:
=HLookup(Sheet1!A1;Sheet3!$A$1:$B$1;1;FALSE)
note that you're using semicolons where you're supposed to use commmas.
the problem in the second try is that the .Range property takes a string as input, so you cant Range(Cells(1,1)) you should do something like .Range("A1:A3")
hope it helps !

Run excel formula through VBA

I am trying to VLOOKUP some value in 2 sheets and if the value is found then i am putting a hyperlink on the Sheet 1 cell to point it to the Sheet 2 cell.
I have written an Excel formula for the same and it is working fine. But I am unable to convert it into a VBA formula. What am I doing wrong?
Excel formula:
=IF(ISERROR(VLOOKUP(RC[7],Sheet2!R1C1:R20C1,1,FALSE)),RC[7],HYPERLINK(CELL("address",INDEX(Sheet2!R1C1:R20C1,MATCH(RC[7],Sheet2!R1C1:R20C1,0))),RC[7]))
VBA formula which i have tried:
Sheets(4).Formula = "= IF(ISERROR(VLOOKUP(RC[7],Sheet2!R4C2:R" & Lrow2 & "C2,1,FALSE)),RC[7],HYPERLINK(CELL(" & """address""" & ",INDEX(Sheet2!R4C2:" & "R" & Lrow2 & "C2,MATCH(RC[7],Sheet2!R4C2:" & "R" & Lrow2 & "C2,0))),RC[7]))"
P.S.: Do not worry about the row and column indexes. I wrote the formula for test file and writing the vba for the master file.
Just a minor mistake you've done.
Sheets(4).Formula = "" represents the formula applied on sheet4.Logically sheet 4 has almost million rows. Where will the formula sit?
Sheet(4).cells(row, column).Formula = ""
Here is one example i have just wrote few min back for sumif
shPivotAdjustmentsIRSPV.Cells(NumRows, NumColumns + 1).Formula =
"=Sum(" & shPivotAdjustmentsIRSPV.Cells(3, NumColumns + 1).Address &
":" & shPivotAdjustmentsIRSPV.Cells(NumRows - 2, NumColumns +
1).Address & ")"
In addition to a range, you need to use the .FormulaR1C1 property if you are going to use R1C1 references:
Sheets(4).Range("A7").FormulaR1C1 = "=IF(ISERROR(VLOOKUP(RC[7],Sheet2!R4C2:R" & Lrow2 & "C2,1,FALSE)),RC[7],HYPERLINK(CELL(""address"",INDEX(Sheet2!R4C2:R" & Lrow2 & "C2,MATCH(RC[7],Sheet2!R4C2:R" & Lrow2 & "C2,0))),RC[7]))"