Error when trying to insert Formula to an ActiveCell - vba

I am writing a small script and I would like to insert a function to a specific cell. I have tried the following piece of code:
end_time = ActiveCell.Offset(0, 2).Address
time_dif = "=TEXT(" + end_time + "-" + st_time + ";""[ωω]:μμ:δδ"")"
found = False
Workbooks("Template.xlsx").Worksheets(1).Range(ActiveCell.Offset(0, 3).Address).Select
'Var = ActiveCell.formula
ActiveCell.formula = time_dif 'Var
The last line in the above code is throwing an error:
'Application-Defined or Object-Defined Error'
The time_dif variable contains the following string:
"=TEXT($H$19-$H$13;"[ωω]:μμ:δδ")"
as seen in the local variables window
I have tried many different ways for the above to make it work but unfortunattely all of them failed.
What it actually worked is putting the exact same formula in another cell. Pause the execution an activate the cell with the formula. Put the formula in the variable Var and then move the activecell to the correct position and insert the variable Var value there.
Var = ActiveCell.formula 'Break point here / Run one step to take formula
ActiveCell.formula = Var 'Move to correct cell manually / Continue execution
Another thing I tried was removing the "=" from the formula and it puts the formula in the cell correctly as string.
Any advise or ideas about this?

The VBE uses English syntaxes.
Try using a sub to get the English syntax, e.g:
Sub ert()
InputBox Prompt:=" ", Default:=Selection.Formula
End Sub
The correct answer thus will be
"=TEXT(" + end_time + "-" + st_time + ",""[ωω]:μμ:δδ"")"
with the "," replacing the ";".

have you tried ActiveCell.FormulaR1C1 ?
Here you might change to include Chr(34), in your string, but as it seems to display correctly, I don't think that's the problem...
"=TEXT(" & end_time & "-" & st_time & ";" & Chr(34) & "[hh]:mm:ss" & Chr(34) & ")"

Related

Works with long type, but not with any other variable type

This is the code, that is bug-free:
Sub Minus()
Dim cell As Long
cell = ActiveCell.Value
Dim offsetcell As Long
offsetcell = ActiveCell.Offset(0, -1).Value
ActiveCell.Formula = "=" & cell & "-" & offsetcell
End Sub
As soon as I change the variable to any other type (preferably Double) the code stops working and bug appears in the concatenated function below.
Any ideas why?
i would like full original value minus adjacent cell (one left).
You are probably casting a decimal comma to text which will break the formula. So, convert using Str that will return a dot as the decimal separator:
ActiveCell.Formula = "=" & Str(cell) & "-" & Str(offsetcell)
That works here.
PS: Don't use native object names (cell) as the name for variables holding completely different values types.

How to put a VBA formula using dynamic variables capturing Address?

I am running a Loop to capture the start of Range and end of Range for a particular scenario. After I find my start range and end range, I want to put it as a formula in a cell. For example:
Cells(1,1).Formula "= Min( startrange:endrange)"
The above code has assumed the variables as text and instead of putting the cell address these variables are handling, it is pasting the formula as text like this : '= Min( startrange:endrange)'
I have no idea and have tried different approaches I could get from internet like below
' cells(4,4).formula = "=Min("&startrage& :"" & endrange & ")""
' Cells(4, 4).Formula = "=Min(startrange.value :endrange)"
'Cells(4, 4).Formula = Application.WorksheetFunction.Min(startrange:endrange)
' Cells(4, 4).Formula = "=Min("&startrange&"&":"& " &endrange&")"
where
startrange = ActiveCell.Offset(1, 3).Address(0, 0)
endrange = ActiveCell.Offset(0, 3).Address(0, 0)
Nothing works.
How can I achieve this? Specially I am also facing error in handling ":".
cells(4,4).formula = "=Min(" & startrage & ":" & endrange & ")"

Formatting a Formula in a String VBA

I have a script that needs to place a formula into a cell but I'm getting a 1004 error from the first part I am sure I formatted something wrong. I had difficulty with the " marks in the string but got those worked out so I'm figuring I'm missing something else. The cells are also unprotected.
Worksheets(CurSheet + 1).Range("D" & Y).Value = "=IF(D52=1,0,IF(C52=" & """Saturday""" & ",0,'" & CurSheet & "!C" & Y & "))"
This is the section that gives the error. If it is removed code works.
"=IF(D52=1,0,IF(C52="
I am not sure what I am doing wrong with this part.
It looks like you're using CurSheet as a sheet index number and as a sheet name.
The index number just returns the relative position of the sheet in the workbook while the name is what you see on the sheet tab (there's also the CodeName but I won't go into that here).
Although I don't fully understand what you're after this code will place a formula on the sheet identified with the sheet index number, so if CurSheet= 1(+1) it will place the formula on the second sheet.
The formula itself will reference the name of the sheet that is before the sheet that the formula appears on (so if the formula is on the second sheet, the formula will reference the first sheet).
Sub Test()
Dim Y As Long
Dim CurSheet As Long
Y = 1
CurSheet = 1
Worksheets(CurSheet + 1).Range("D" & Y).Formula = _
"=IF(D52=1,0,IF(C52=" & """Saturday""" & ",0,'" & Worksheets(CurSheet).Name & "'!C" & Y & "))"
End Sub
Hope I made that clear enough. :)
You need to declare that you are inputting a formula, not a value:
Change:
Worksheets(CurSheet + 1).Range("D" & Y).Value
To:
Worksheets(CurSheet + 1).Range("D" & Y).Formula

Introduce variables in recorded VBA macro

I recorded part of this macro in Excel:
Cells(x, i).Select
Selection.FormulaArray = _
"=SQRT((MMULT(MMULT(TRANSPOSE(R2C14:R9C14),'Monthly Covariance y1'!R[12]C[0]:R[19]C[7]),'Portfolio Vola per Month'!R2C14:R9C14)))"
In the middle term " 'Monthly Covariance y1'!R[12]C[0]:R[19]C[7])" I want to express the bold numbers as variables. 0 should be j and 7 should be j+7.
When I try to replace the hard numbers by variables, Excel returns "Unable to set FormulaArray property of the Range class".
Any idea on how I can work around this problem?
Many thanks.
Just close the formula, add variables, and open again:
"=SQRT((MMULT(MMULT(TRANSPOSE(R2C14:R9C14),'Monthly Covariance y1'!R[12]C["& j & "]:R[19]C["& j + 7 & "]),'Portfolio Vola per Month'!R2C14:R9C14)))"
By "close the formula", I mean close with a ", then use & to connect the variables, then "reopen" with ". Simple example, with j being a row number, say 5:
myRange.FormulaR1C1 = "=Sum(A" & j & ":A" & j & ")"
is equivalent to
myRange.FormulaR1C1 = "=Sum(A5:A5)"
Also, this is another issue altogether, but try to avoid using .Select

VBA for Excel - building .Formula with contents containing quotation marks

I'm coding a project in VBA for Excel, which loops to a file, matches the 'code' for each of the quantities, and then feeds all the matches for that code to a user defined function, which goes onto the Excel sheet.
I can read the info, sort it so postdata(nr_of_datafield, nr_of_item) returns me the row in the source sheet on which the value is listed. Based on this, I need to create (through .Formula) a syntax like this:
=formul(raming!J104) (if there's only one occurence)
=formul(raming!J104;"+";raming!J108) (etc., always adding the same extra if there's multiple occurences)
=formul(raming!J104;"+";raming!J108;"+";raming!312;"+";raming!J403) etcetera, with always needing to get the previous values from what's already in Cells.Formula.
Based on this check:
Code:
Right(Workbooks(meetstaatfile).Sheets("HOR_raming").Cells(lusteller12, 9 + CInt(postdata(3, eerstepositie)) * 3).Formula, 2) = "()"
I can detect if there is already any contents added here. If not (meaning the check for () ending is positive), I replace with this:
Code:
Workbooks(meetstaatfile).Sheets("HOR_raming").Cells(lusteller12, 9 + postdata(3, eerstepositie) * 3).Formula = "=formul('raming'!J" & postdata(2, eerstepositie) & ")"
To create a formula that looks like: =formul(raming!J104)
(the '104' in this example is the output from postdata(2,eerstepositie)
However, if it doesn't trigger for the () ending, there already is a value, and I need to extend the formula to something like this: =formul(raming!J104;"+";raming!J108)
I've been trying to figure out how to do this by replacing ')' with the block I want added, but I cannot get it to work to input the quotation marks. ('formul' is very similar to concatenating text).
How can I make a variation of the codeline above that lets me alter the cell input? Either by a Replace() like I was trying, or reading what's between the formul() brackets and rebuilding the formula?
If you need to have quotation marks as content within a string literal in VBA, you have to double them. See: http://msdn.microsoft.com/en-us/library/ms234766.aspx
.Formula = "=formul('raming'!J" & 104 & ",""+""," & "'raming'!J" & 108 & ")"
Or with your postdata:
.Formula = "=formul('raming'!J" & postdata(2, eerstepositie) & ",""+""," & "'raming'!J" & postdata(2, whatevergets108) & ")"
I don't know, whether I have understood it right, but if you need to concatenate the formula in dependence of the contents of an array, then this can be achieved like so:
Sub test()
'one occurrence
postdata = [{0;104}]
sFormulaString = getFormulaString(postdata, 2)
MsgBox sFormulaString
'two occurrences
postdata = [{0,0;104,108}]
sFormulaString = getFormulaString(postdata, 2)
MsgBox sFormulaString
'three occurrences
postdata = [{0,0,0;104,108,312}]
sFormulaString = getFormulaString(postdata, 2)
MsgBox sFormulaString
End Sub
Function getFormulaString(postdata As Variant, nr_of_datafield As Long) As String
sFormula = "=formul("
For i = LBound(postdata, 2) To UBound(postdata, 2)
sFormula = sFormula & "'raming'!J" & postdata(nr_of_datafield, i) & ",""+"","
Next
sFormula = Left(sFormula, Len(sFormula) - 5) & ")"
getFormulaString = sFormula
End Function
Hm, or is the real need, to append new formula parts into an existing formula? If so, the following code will append a new part into the Formula in A1 every time it runs.
Sub test2()
postdata = [{0;104}]
sFormula = Range("A1").Formula
If sFormula = "" Then sFormula = "=formul("
If Right(sFormula, 1) = ")" Then sFormula = Left(sFormula, Len(sFormula) - 1) & ",""+"","
sFormula = sFormula & "'raming'!J" & postdata(2, 1) & ")"
Range("A1").Formula = sFormula
End Sub
Greetings
Axel