I am using the following code to add something to a Formula in VBA (for debugging purposes I am using the variable currentFormula, instead of doing it directly):
currentFormula = Range("A" & row).Formula
currentFormula = currentFormula & "+" & CStr(difference)
Range("A" & row).Formula = currentFormula
When going through the code step by step, the variable currentFormula has the correct value before the final step, e.g. "=A1/A2+0.5". However, then the script Fails with runtime error 1004. When I am Setting currentFormula manually to something like "=10+10", the script works.
CStr formats the number according to the current system locale.
Formula accepts formulas in English.
The function that converts numbers to strings in an invariant way is Str. Note that it prepends a space to positive numbers which you might want to remove:
currentFormula = currentFormula & "+" & LTrim$(Str$(difference))
Related
I am trying to dynamically construct a formula based on an array that I have generated from a cell (separated by commas), as there is a varying amount of elements in the array I need to append a new "formula block" with the updated element to use in a if statement that is generated after the for each loop. VBA is throwing a type mismatch error in the InvestigateFormula = line, here is my code:
For Each Type In ToIgnore()
InvestigateFormula = "(ISNUMBER(SEARCH(*" & ToIgnore(Type) & "*," & _
AssetTypesCol & "2)),"
FullFormula = InvestigateFormula & FullFormula
Next Asset
FinalInvestigateFormula = "=IF(OR" & FullFormula & "),""Ignore"", """")"
ActiveCell.Formula = FinalInvestigateFormula
Please let me know if there is an easier way of doing this or how I might be able to correct the above code. Btw I am not declaring a variant I am simply declaring ToIgnore() as String and using the split function from the variable which contains the comma separated values to generate the array/items to loop over.
"Type" is a reserved name? Try strType instead?
I know it's been asked several times, but I just don't get it.
I'd like to know the rules in order to correctly build VBA code which incorporates formulas and variables in a VBA Evaluate function.
This works ok:
stringa_per_mesi = "=DATEDIF(""" & d1 & """,""" & WorksheetFunction.EDate(d1, 12) & """,""ym"")"
mesi = Application.Evaluate(stringa_per_mesi)
I have to write a more complex formula with Evaluate but I get lost, so I have to solve the doubts I have.
In the above example, why couldn't I just write
stringa_per_mesi = "=DATEDIF(d1, & WorksheetFunction.EDate(d1, 12) & """,""ym"")"
and why this works
WorksheetFunction.EDate(d1, 12)
even without quotation marks here (d1, 12)?
Thank you!
I have a macro that prompts me for a SQL query (unless it was called by another Sub, in which case it uses the argument that was passed into its optional string parameter as the query) and then executes the query against my Teradata SQL database.
It works fine, unless there's a column alias containing a space in the query.
Example query:
SELECT 2 + 2 AS "Query Result";
Error:
Run-time error '1004':
[Expression.Error] The name 'Source' wasn't recognized. Make sure it's spelled correctly.
The line of code which I believe is the culprit is as follows (my apologies for the readability-- I recorded the macro, modified it just enough to get it to work somewhat dynamically and then haven't touched it since).
ActiveWorkbook.Queries.Add Name:=queryName, formula:= _
"let" & Chr(13) & "" & Chr(10) & " Source = Odbc.Query(""dsn=my-server-name"", " & Chr(34) & code & Chr(34) & ")" & Chr(13) & "" & Chr(10) & "in" & Chr(13) & "" & Chr(10) & " Source"
I assume it has to do with the fact that the example query above has double quotes for the alias, which are confusing the syntax when trying to be interpolated. Any help would be greatly appreciated!
Here's what the string for the formula is set to in this line:
ActiveWorkbook.Queries.Add Name:=queryName, formula:=<string here>
after all the chr() and concatenation are done:
let
Source = Odbc.Query("dsn=my-server-name", "<code>")
in
Source
That token <code> is replaced by whatever is in your variable code. So I suspect you are correct in that this formula would need to have it's double quotes escaped fully.
In other words this string you are building form Formula is going to be evaluated as code itself, and even in that evaluation it will be passing more code (your SQL) onto the Teradata server to be evaluated there.
You are in code inception. VBA code writing powerquery code writing Teradata code.
Understanding that and guessing a bit here, I'm thinking your current code variable looks something like:
code="SELECT 2 + 2 AS ""Query Result"";"
Your double quotes are already escaped for VBA. BUT because you have to survive another round of eval in powerquery you need to escape once again. Instead:
code="SELECT 2 + 2 AS """"Query Result"""";"
*I think...
I seem to be having a type mismatch error in the below formula. Numbering, Approval, PeakShare, and RampUp are all stored as ranges, app as an integer. I believe I have escaped my quotes correctly in trying to include the value of 'app'. But I get a "Type mismatch" error in return. I have also tried including a non-variable integer and receive an "Object defined or application defined error." I have read some things about the use of indirect and approval in Excel formulas but haven't found much out there with its use in VBA, is this the problem?
formulaUp = "=IF(" & Numbering.Address(True, False) & "<" & Approval.Address & ","""", " & PeakShare.Address & " * " & RampUp.Offset(0, -"" & app & "" + 1).Address(True, False) & ")"
The type mismatch comes from
RampUp.Offset(0, -"" & app & "" + 1)
The second argument you are trying to pass to Offset does not make much sense, and throws because according to operator precedence it's (-"") & app & ("" + 1), and neither of the bracketed expressions can be calculated.
Apparently you meant
RampUp.Offset(0, -app + 1)
So I am using Instr with Evaluation and facing some difficulties
The code is as follows
myIneq=">"
myString1="Hello"
myString2="el"
Evaluate( "Instr(" & myString1 & "," & myString2 & ")" & myIneq & cstr(0)
I am getting an Error 2029. Based off this msdn link I am assuming it is trying to evaluate "Hello" as a variable name. What is the work around for this, I know there must be one.
Thanks
I infer from the Error 2029 (#NAME?) and the link that you're using Excel. In this case the answer is simple. Application.Evaluate evaluates Excel expressions, not VBA code. That is, any functions you call in your expression have to be things you could call from an Excel formula. (And you're correct that Excel is trying to evaluate the value of a symbol it doesn't recognize, and is thus giving you back a #NAME? error.)
There is an Excel worksheet function, FIND, that does pretty much the same thing that the VBA function Instr does, so if your example is not too simplified, that might be all you need to do.
I just typed this into the Immediate window:
x="Hello"
y="el"
?Evaluate("FIND(""" & y & """, """ & x & """)")
2
ineq = ">"
?Evaluate("FIND(""" & y & """, """ & x & """)" & ineq & "0")
True
and it seems to work.
Note that Evaluate is a function, so it expects to receive a string argument, and then return what that string evaluates to if treated as an Excel formula-syntax expression. In your example, you don't seem to be doing anything with the return value, so I thought I'd mention it.
"Evaluate" doesn't understand all excel functions.
For example, trying to evaluate "instr" will give an Error 2029. But there is a nice workaround:
"evaluate" recognizes all added vba functions of your excel sheet
so just wrap a single-line function around the reluctant function.
Code will be similar to this:
Sub test()
MsgBox Evaluate(" Instring(""Hello"",""el"") ")
Msgbox "\o/ ! ... I owe a beer to someone out there"
End Sub
Function Instring(a, b)
'make instr visible to 'evaluate'
Instring = InStr(a, b)
End Function
You're evaluating the string InStr(Hello,el).
Obviously, that's not what you want.
You need to use a quoted string literal.