Using string variables within a formula in VBA - vba

I do not understand why this code doesn't work:
Cells(i, formula_col_index).Value = "=IF(" & time_location & "<>" & time_benchmark & ",""ERROR"",""OK"")"
where
time_location=" 17:00:00",
time_benchmark=" 17:30:00"
It keeps throwing application-defined (or object-defined) error.
Thanks in advance.

Since your variables time_location and time_benchmark contains string values, you should include them in double quotes when using formula:
Cells(i, formula_col_index).Value = "=IF(""" & time_location & """<>""" & time_benchmark & """,""ERROR"",""OK"")"

Related

Excel VBA - insert formula in a set of rows with variable reference directly or replacing a string for example "\=" with "="

I have the goal to write a formula in a set of rows. Some references in the formula have to change each row.
I implemented the following script:
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 0 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."";A" & i & ";IF(Q" & i & "=""Ist"";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=""Lz."";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=""Ist+Lz.-Bedarf"";OFFSET(A" & i & ";-3;0);)))))"
Let temprng = "M" & i
Range(temprng).Select
ActiveCell.Value = "\=" & formcolM
next i
With this script I am writing a string each row in my excel table at column M.
I noticed that if the formula hasn't the symbol "\" , you can find an error .
In order to avoid the error I thought to leave the symbol "\" and to use a trick deleting it after (because I don't know how to solve with R1C1 formula. I read some answers on Stackoverflow, but unfortunately I did not understand )
The replacing script after the for cycle:
Columns("M:M").Replace What:="\=", Replacement:="=", LookAt:=xlPart
The strange thing is that the macro doesn't delete it.
Infact when the script finishes , it seems that nothing happened, without errors. But if I want substitute "\=" with another symbol, for example "*", the replacing script works.
I did not understand if the problem is :
the replace method did not recognized the symbol "=" to search
I cannot use the replace method because the symbol "=" disturbs in some way , I don't know in what.
OR, is there another simplest way to get this task done?
Someone could help me in order to fix? I should have the formula working in the column M , automatically with vba (not with another formula in the excel sheet) .
Thanks in advance for your time.
We can apply the formula directly. The issue is that vba is very US-EN Centric and all formula when using the .Formula needs to be in that format.
Also since your formula refers to values in a row 3 above the one in which it is put we need to start the loop at 4 not 0. There is no row 0
There are two ways, in US-En format with English functions and , as the deliminator using .Formula:
Dim i As Integer
For i = 4 To 100
Range("M" & i).Formula = "=NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."",A" & i & ",IF(Q" & i & "=""Ist"",OFFSET(A" & i & ",-1,0),IF(Q" & i & "=""Lz."",OFFSET(A" & i & ",-2,0),IF(Q" & i & "=""Ist+Lz.-Bedarf"",OFFSET(A" & i & ",-3,0),)))))"
Next i
Or using .FormulaLocal and the formula as you would write it in your native tongue.
Dim i As Integer
For i = 4 To 100
Range("M" & i).FormulaLocal = "=NUMERO.VALORE(SE(Q" & i & "=""Bedarf kum."";A" & i & ";SE(Q" & i & "=""Ist"";SCARTO(A" & i & ";-1;0);SE(Q" & i & "=""Lz."";SCARTO(A" & i & ";-2;0);SE(Q" & i & "=""Ist+Lz.-Bedarf"";SCARTO(A" & i & ";-3;0);)))))"
Next i
By the time I got this worked out, Scott already had an answer. I just wanted to post your original code modified to work. I would suggest his method.
Sub TestScript()
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 4 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=" & "Bedarf kum." & ";A" & i & ";IF(Q" & i & "=" & "Ist" & ";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=" & "Lz." & ";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=" & "Ist+Lz.-Bedarf" & ";OFFSET(A" & i & ";-3;0);)))))"
temprng = "M" & i
Sheets("Sheet1").Range(temprng).Select
ActiveCell.Value = " = " & formcolM
Next i
End Sub

VBA: Dims inside a Vlookup

I'm trying to use a Vlookup with the line:
wRange.FormulaR1C1 = "=VLOOKUP(RC[-" & (vCol - 1) & "],'" & vSheet & "'!C[15]:C[16],2,FALSE"
where vCol as Integer = 9 and vSheet as String = 082015
So basically, that line can be rewritten as:
wRange.FormulaR1C1 = "=VLOOKUP(RC[-8],'082015'!C[15]:C[16],2,FALSE)"
However, I'm getting an "Application-defined or object-defined error" during run-time.
Do you see what I'm doing wrong?
Thanks.
"=VLOOKUP(RC[-" & (vCol - 1) & "],'" & vSheet & "'!C[15]:C[16],2,FALSE)"
Note missing bracket at the end

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 !

VBA SumProduct Runtime Error 13

As a part of a much longer code, I am trying to include a SumProduct
Dim SumPr as Variant
SumPr=Application.WorksheetFunction.SumProduct(((Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("A:A")) = Range("A" & i)) * ((Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("D:D")) = "PH") * (Workbooks(Source2).Sheets("Prices_EUR_Adj").Range(ColLtr & ":" & ColLtr)))
MsgBox SumPr
However, I keep getting Runtime Error 13 for some reason. Any idea what is wrong? Source2 is properly defined, and ColLtr is letter conversion of column number I got from match; it also works ok as checked by message box.
Try using the Evaluate function instead:
Dim SumPr As Variant
SumPr = Application.Evaluate("SUMPRODUCT(--(" & Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("A:A").Address & "=" & Range("A" & i).Address & ")," & _
"--(" & Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("D:D").Address & "=""PH"")," & _
Workbooks(Source2).Sheets("Prices_EUR_Adj").Range(ColLtr & ":" & ColLtr).Address & ")")
MsgBox SumPr
I'm sure the WorksheetFunction.SumProduct will also work, but I was able to get the Evaluate function working easier.

application.worksheetfunction.sum not evaluating string

I have the following code in my procedure built up to be evaluated within a much larger loop
CalculationHoldArray(Loopcount) = "'[" & Usefile1.Name & "]" & _
Worksheet1 & "'!" & Cells1 & ",'[" & Usefile2.Name & "]" & _
Worksheet2 & "'!" & Cells2
Sheets("ECAP PARAMETER INPUTS").Cells(31, "F").Value =
Application.WorksheetFunction.Sum(CalculationHoldArray(Loopcount))
The string returned for the array is:
'[Control Model v1.35- nonfunctional.xlsm]Input'!E2, _
'[Control Model v1.35- nonfunctional.xlsm]Input'!E3
But the application.worksheetfunction.sum is returning an error 1004. "Unable to get the sum property of the worksheet class". Anyone know what the issue is that it won't let me use the sum property here?
Instead of using the Application.Worksheet.Function command, simply use the Evaluate command, which requires adding in the "sum" and brackets to make it a valid formulae.
But I have found a solution- instead of using the application.worksheet.function command, I can simply use the "EVALUATE" command, just required adding in the "sum" and brackets to make it a full formulae –