Formula inside a variable - excel

I have the following question, is it posible to insert a formula inside a variable in VBA Excel to use this variable after?
For example:
MinO = "=MIN(" & .Cells(3, 7 + NumSheet).Address(False, False) & ":" & .Cells(3, 9 + NumSheet).Address(False, False) & ")"
For N = 1 To NumSheet + 1
.Cells(4, 5 + N).Value = 80 * ((.Cells(3, 8 + NumSheet).Value - .Cells(3, 5 + N).Value) / (.Cells(3, 8 + NumSheet).Value - MinO))
.Cells(4, 5 + N).Font.Bold = True
Next N
So MinO is a variable with a formula inside, I know in Range().Formula it works but how can I make it work using a variable?
I know there is also the Application.WorksheetFunction.Min but I want to see if it's posible doing it the other way as WorksheetFunction sometimes give me some errors.
Thank you so much for your answers!

You can do this, but therefore you need the Evaluate() function. (The URL refers to the official documentation of that function)
So, in your case, you might use: (seems not to be completely correct, so I'll put it in comment)
' .Cells(4, 5 + N).Value = 80 * ((.Cells(3, 8 + NumSheet).Value - .Cells(3, 5 + N).Value) / (.Cells(3, 8 + NumSheet).Value - Evaluate(MinO)))
As mentioned in below comments, the following seems to be the correct approach:
MinO = Evaluate("=MIN(" & .Cells(3, 7 + NumSheet).Address(False, False) & ":" & .Cells(3, 9 + NumSheet).Address(False, False) & ")")

Usually when I work with formulas from excel i write them in cell (check that everything works) and then in VBA immediate window (CTRL+G) I type
? Activecell.Formula
or
? Activecell.FormulaR1C1
And it displays formula that you need... That is good start then you start changing parts to reflect your desired variable changes.
Remember that this output is string and in code needs to start and end with 1x", when you want to add string in formula you need to add "" also sometimes you need to add """" and """ for strings in string... :)

I don't think this will work, as it is basically just a text string. I believe that you try to look into why the Application.WorksheetFunction is giving errors instead, or creating your own function if you have some special cases that the worksheet function cannot handle.

Related

Inserting a formula using a macro

I am attempting to insert an IF formula using a macro and I can't seem to get the syntax correct. Trying to insert quotes has me confused, attempting to insert "" I have to use """"".
This is the IF function I need to insert
=IF(P14&Q14&R14<>"","<>","")
The macro creates a new row every time it is called, therefore the next formula inserted under it would be
=IF(P15&Q15&R15<>"","<>","")
I get the next empty row using
iRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows,
_ SearchDirection:=xlPrevious, LookIn:=xlValues.Row + 1
Yet using this insert method and syntax I get a type mismatch error.
.Cells(iRow, 3).Value = "=IF(P" + iRow + "&Q" + iRow + "&R" + iRow + "<>"""""," + ""<>"",""""")"
Can someone please advise as to why I am receiving a type mismatch error?
Thanks for your help!
Firstly, do not use + for concatenation. Use &. In some particular cases, you may have problems.
Secondly, it is good to use .Formula instead of .Value...
And the formula string should be:
.Cells(iRow, 3).Formula = "=IF(P" & iRow & "&Q" & iRow & "&R" & iRow & "<>""""," & """<>"","""")"
Five """"" makes sense only at the end of the string... Four to double the existing one and the fifth for string termination.
You could use:
.Cells(iRow, 3).Value = Replace("=IF(PX&QX&RX<>"""",""<>"","""")", "X", iRow)

VBA,Combine .Formula with VBA

I have the following vba code which puts a formula in a cell.
.Range("D" & lastrow + 1).Formula = "=INDEX(Spread!$C:$C, MATCH(1,INDEX((A330 = Spread!$A:$A) * (""Stack"" =Spread!$B:$B),),0))"
How can I change A330 in my formula to vba code like Worksheets("Manager").Range("C2").Value
Just concate it like a normal string using the & operator. Since you are not joining text ,but rather a VBA object, do not wrap quotes around the object.
"=INDEX(Spread!$C:$C, MATCH(1,INDEX((" & Worksheets("Manager").Range("C2").Value & "= Spread!$A:$A) * (""Stack"" =Spread!$B:$B),),0))"
You can also store the data in a variable and use it instead of A330. This way you can always use newly created variable inside your code anytime anywhere in your code
myData = Worksheets("Manager").Range("C2").Value
.Range("D" & lastrow + 1).Formula = "=INDEX(Spread!$C:$C, MATCH(1,INDEX((myData = Spread!$A:$A) * (""Stack"" =Spread!$B:$B),),0))"

get the differences between 2 Integer columns into third column

I have to calculate the difference between the values of 2 columns(firstCol and lastCol) and set those differences in a different column(NextColumn). The row count keeps changing, so I have to calculate the rowCount before calculating the difference. I'm trying to write a loop using Range so that the difference can be calculated but it doesn't seem to work.
For i = 3 To lastRow
Range(Cells(3, NextColumn), Cells(lastRow, NextColumn)).FormulaR1C1 = "=Range(Cells(i, firstCol),Cells(i,firstCol)).Value - Range(Cells(i, lastCol),Cells(i,lastCol)).Value"
Next i
Any help would be greatly appreciated!
Thank you
Nick
For any input of "i" into the formula, you need to use " & i & " when using using a formula="", such as:
"=A" & i & "+B" & i
When you change to just a formula that doesn't input a formula to the cell (math happens in VBA), you can ignore the Excel formatting and "" blocking, such as:
= Cells(i,"A").Value + Cells(i,"B").Value
Make sure to use your loop variable where appropriate, so that you would have an outcome in a loop like:
Dim i as Long
For i = 1 to 10
Cells(i,"C").Formula = Cells(i,"A").Value + Cells(i,"B").Value
Next i
Why looping ? Unless I misunderstood the question, something like this should do the trick:
Range("X3:X"& lastrow).Formula = "=C3-D3"
The formula will adjust.
vba needs to be outside the quotes and you do not need the loop:
Range(Cells(3, NextColumn), Cells(lastRow, NextColumn)).Formula = "=" & Cells(3, firstCol).Address(0, 0) & "-" & Cells(3, lastCol).Address(0, 0)
No loop needed. Excel will change the relative references as needed.

Excel VBA .Trim function changes . to ,

Earlier today I was cleaning up data, using the .trim() vba function. Though it caused . to be changed to , and I have no idea why.
Cells(rw, j).Value = Trim(Cells(rw, j).Value)
Is all I did, and it changed values as follows:
5.2 -> 5,2
One might think that is due to the local settings, though the same column contains values like 3(6.1) which are not messed up.
Thanks in advance
Go to File - Options - Advanced and look for Use system separators. You want the decimal separator to be . and the Thousands separator to be ,
You can also change these in VBA using the following code:
Application.DecimalSeparator = "."
Application.ThousandsSeparator = ","
Application.UseSystemSeparators = False
As you don't want to changes these setting, change your code to:
Cells(rw, j).Value = "'" & Trim(Cells(rw, j).Text)
.Text will give you the string version of what is in the cell rather than attempt to convert it to a number (if it looks like a number).
If you don't want to change your global system/excel settings for this one application, you could try forcing the value to text with something like:
With Cells(rw, j)
.NumberFormat = "#"
.Value = Trim(Cells(rw, j).Value)
End With
Alternatively, based on your comment:
With Cells(rw, j).Value = "'" & Trim(Cells(rw, j).Value)
You can try this:
Dim temp As String
temp = Cells(rw, j).Value
temp = Trim(temp)
Cells(rw, j).Value = temp
Unfortunately I can't test it.

(VBA) dynamic use of embedded excel functions

I am tryin to postprocess data. As well I got column which have hour minute and second. With VBA I created a loop to go through every single row in a for loop.
For i = 2 To Max
Range("GE" & CStr(i + Offset)).Formula = "=TIME(AK & CStr(i + Offset);AL & CStr(i + Offset);AM & CStr(i + Offset))"
Next i
It comes to Run-time error 1004: Application defined or object defined error.
How can we edit this to be working?
For i = 2 To Max
Range("GE" & CStr(i + Offset)).Formula = "=TIME(AK" & CStr(i + Offset) & ",AL" & CStr(i + Offset) & ",AM" & CStr(i + Offset) & ")"
Next i
The loop variable needs to be "outside" the string you're entering as a formula to allow it to be built correctly.
This fixes the typo in your code, but you should consider setting the range specifically for the worksheet.
I've also changed your semicolons to commas as that's how the TIME function works in Excel here, but if your settings are different you might need to revert that.

Resources