How do I convert this Excel formula into VBA code? - vba

'I am using this formula in an Excel worksheet, in cell A6. It is working fine.
=IF(O6="Hand","Manual Entry",IF(O6="JET",R6,IF(O6="COKE","Red Bull",IF(O6="Freight","Logistics",IF(O6="TAX","Tax",IF(O6="TRANSFER COST","Transfer Cost Transactions",IFERROR(IF(FIND("INV#",R6,1)>=1,MID(R6,FIND("INV#",R6,1),10),""),"")))))))
Now, my question is: how do I convert this to VBA? I have tried recording it, and the code is as follows:
ActiveCell.FormulaR1C1 = _
"=IF(RC[14]=""Hand"",""Manual Entry JE"",IF(RC[14]=""JET"",RC[17],IF(RC[14]=""COKE"",""Red Bull"",IF(RC[14]=""FREIGHT"",""Logistics"",IF(RC[14]=""TAX"",""Tax"",IF(RC[14]=""TRANSFER COST"",""Transfer Cost Transactions"",IFERROR(IF(FIND(""INV#"",RC[17],1)>=1,MID(RC[17],FIND(""INV#"",RC[17]" & _
"""""),"""")))))))"
When I run this, I am receiving Run Time Error 1004: Application-defined or object-defined error.So I Changed this to something like this, this doing same as above formula except the find option, everything is running fine.
![VBA For Above formula][Any Help on the find?]
End sub.How do i get the fine option in the above VBA code.`

This works for me:
Range("L6").Formula = "=IF(O6=""Hand"",""Manual Entry"",IF(O6=""JET"",R6,IF(O6=""COKE"",""Red Bull"",IF(O6=""Freight"",""Logistics"",IF(O6=""TAX"",""Tax"",IF(O6=""TRANSFER COST"",""Transfer Cost Transactions"",IFERROR(IF(FIND(""INV#"",R6,1)>=1,MID(R6,FIND(""INV#"",R6,1),10),""""),"""")))))))"
This is just your original Excel formula, but with the " characters escaped as "".

You need to escape your quotes.
ActiveCell.Formula = "=IF(O6=""Hand"",""Manual Entry"",IF(O6=""JET"",R6,IF(O6=""COKE"",""Red Bull"",IF(O6=""Freight"",""Logistics"",IF(O6=""TAX"",""Tax"",IF(O6=""TRANSFER COST"",""Transfer Cost Transactions"",IFERROR(IF(FIND(""INV#"",R6,1)>=1,MID(R6,FIND(""INV#"",R6,1),10),""""),"""")))))))"
And use .Formula since you're using specific cell names that are not relative to the currently selected cell.

Related

"checked" statement causing error on a vba macro for excel

So i need to add a formula to an entire column using a macro,
so far i have:
Range("S2:S" & lastRow).Formula = "=IF(TRIM(N2)="checked",M2,IF(LEN(P2)>=60, P2, IF(LEN(SUBSTITUTE(R2,CONCATENATE(" ", $J$2),""))>=60,SUBSTITUTE(R2,CONCATENATE(" ", $J$2),""),R2)))"
Which is supposed to take several values of different cells and form a new one, the problem is that the code sends an error "Syntax Error" but if i put the formula in a cell in excel the formula works perfectly.
Any idea on what could be causing the error? i think it could be linked with how its writen and how vba reads it.
In VBA you must double-up all the quotes inside, viz (there might be other issues, I haven't checked). I expect a google search would have solved this for you.
Range("S2:S" & lastRow).Formula = "=IF(TRIM(N2)=""checked"",M2,IF(LEN(P2)>=60, P2, IF(LEN(SUBSTITUTE(R2,CONCATENATE("" "", $J$2),""""))>=60,SUBSTITUTE(R2,CONCATENATE("" "", $J$2),""""),R2)))"

1004 error when trying to run a macro that applies to a table

I have an existing table. I want to add a new column next to it, with a formula in it so that the formula adds a new column and fills in all the values.
This is a two-page worksheet. Table1 is on another page than the table we're working with, but has the master data it draws from.
I recorded a macro of the formula I used to produce this, but when I try to run it, I get
Run time error '1004': Application-defined or object-defined error.
The code I'm using is below:
Range("B2").Select
ActiveCell.FormulaR1C1 = "=IF(INDEX(Table1,MATCH([#Listing],Table1[Property],0)," & _
"MATCH(""Status"",Table1[#Headers],0))=""for sale"",""seller""," & _
"IF(INDEX(Table1,MATCH([#Listing],Table1[Property],0)," & _
"MATCH(""Status"",Table1[#Headers],0))=""for lease"",""landlord""," & _
"IF(INDEX(Table1,MATCH([#Listing],Table1[Property],0)," & _
"MATCH(""Status"",Table1[#Headers],0))=""for sale or lease"",""seller / landlord""" & _
"X(Table1,MATCH([#Listing],Table1[Property],0)," & _
"MATCH(""Base Rent/Mo"",Table1[#Headers],0))>0,""landlord"",""seller""))))"
Range("B1").Select
Things I've checked so far:
All the names match (i.e. Table1 is a valid name, and all the headers are correctly named)
The formula works exacly as I want to if I just type it in and hit 'enter'
I've looked for similar issues here, and the most similar seem to be some problems with Pivot tables, but the solutions don't seem to be applicable to my problem
(The reason I'm using VBA for this is that this is one part of a multi-step process that I'm trying to automate to make it simpler to run a complicated report from a large set of data.)
EDIT: Additional fixes I tried:
Moving the master data table to the same sheet as my 'target' table to see if it would work if the two were on the same worksheet. No go.
When you need to use quotes inside quotes like in "MATCH(""Status"", which I suppose you are trying to output Match("Status" try using "MATCH("&Chr(34)&Status&Chr(34)
Chr(34) outputs the " symbol. Otherwise it would return MATCH(Status (without quotes)
There were two separate issues.
First, I was recording the macro and apparently, Excel will not record formulas longer than a certain length properly. This limit is greater than 407 (the longest formula I got to auto capture), but shorter than 467 characters. A similar problem was discussed on this Mr. Excel post. This also was why part of the "INDEX" was missing, as BruceWayne pointed out.
In addition, it was necessary to switch from .FormulaR1C1 to .Formula to get it to work correctly, as R3uK had suggested.
The final code ended up as follows:
Range("B2").Select
ActiveCell.Formula = _
"=IF(INDEX(Table1,MATCH($A2,Table1[Property],0),MATCH(""Status"",Table1[#Headers],0))=""for sale"",""seller"",IF(INDEX(Table1,MATCH($A2,Table1[Property],0),MATCH(""Status"",Table1[#Headers],0))=""for lease"",""landlord"",IF(INDEX(Table1,MATCH($A2,Table1[Property],0),MATCH(""Status"",Table1[#Headers],0))=""for sale or lease"",""seller / landlord"",IF(INDEX(Table1,MATCH($A2,Table1[Property],0),MATCH(""Base Rent/Mo"",Table1[#Headers],0))>0,""landlord"",""seller""))))"
Range("B3").Select

Excel VBA .FormulaArray Error

The error is a 1004 error but I don't understand why. The formula in the cell would be:
{=INDEX(KPI!A:AQ,MATCH(1,(KPI!A:A=Monday!$K$1)*(KPI!C:C=Monday!B4),0),37)+INDEX(KPI!A:AQ,MATCH(1,(KPI!A:A=Monday!$K$1)*(KPI!C:C=Monday!B4),0),38)-INDEX(KPI!A:AQ,MATCH(1,(KPI!A:A=Monday!$K$1)*(KPI!C:C=Monday!B4),0),39)}
To get this formula into a macro I simply used the recording tool but it did not work.
Selection.FormulaArray = _
"=INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),37)+INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),38)-INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),39)"
As long as you insist on doing things the hard way,
Option Explicit
Sub wqer()
With ThisWorkbook
.Worksheets("KPI").Name = "K"
.Worksheets("Monday").Name = "M"
'geez - decide what cell you want without Selection¹ !!??!!
Selection.FormulaArray = _
"=INDEX(K!C[-3]:C[39],MATCH(1,(K!C[-3]=M!R1C11)*(K!C[-1]=M!RC[-2]),0),37)+INDEX(K!C[-3]:C[39],MATCH(1,(K!C[-3]=M!R1C11)*(K!C[-1]=M!RC[-2]),0),38)-INDEX(K!C[-3]:C[39],MATCH(1,(K!C[-3]=M!R1C11)*(K!C[-1]=M!RC[-2]),0),39)"
.Worksheets("K").Name = "KPI"
.Worksheets("M").Name = "Monday"
End With
End Sub
Renaming your worksheets back and forth puts your formula under the built-in character limit² noted by Axel Richter for the time it takes to insert the array formula into the cell. This will put an undue calculation demand on your workbook but it may be an acceptable solution for you. Consider changing the application's calculation mode to manual for the duration of the operation.
.¹ See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.
² See Range.FormulaArray property.
You can also try this(
please don't run it from the VBE, try to run it from sheets environment. Go to Developer-Macros-Your Macro -Run or Run it from a button or shortcut and it will work without problem):
Selection.Formula = _
"=INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),37)+INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),38)-INDEX(KPI!C[-3]:C[39],MATCH(1,(KPI!C[-3]=Monday!R1C11)*(KPI!C[-1]=Monday!RC[-2]),0),39)"
SendKeys "{F2}"
SendKeys "^+{ENTER}"

Runtime Error 1004 Copy Formula Array

I have the following array formula in cell B2 in my Excel spreadsheet:
{=IF(COUNT(IF(ISNUMBER(A30:A1000);IF(B30:B1000>A30:A1000-1;A30:A1000)))>=COUNT(IF(ISNUMBER(A30:A1000);COUNT(B30:B1000>A30:A1000-1;A30:A1000)));COUNT(IF(ISNUMBER(A30:A1000);COUNT(B30:B1000>A30:A1000-1;A30:A1000))))}
Now I want to use the following VBA code to copy this code into cell A2:
Sheets("Sheet1").Range("A2").FormulaArray = Sheets("Sheet1").Range("B2").Formula
However, when I use this code I get runtime error 1004.
Do you have any idea how to solve this issue?
Your array formula is too long to pass along like that as the Range.FormulaArray property.
You don't need to keep repeating all of the conditions. As you cycle through rows 30 to 1000, if the first or second condition fails, the remainder of the formula for that cycle is not processed. IFs in a formula stop processing at the first FALSE.
=IF(COUNT(IF(ISNUMBER(A30:A1000), IF(B30:B1000>A30:A1000-1, A30:A1000)))>=COUNT(B30:B1000>A30:A1000-1,A30:A1000),COUNT(B30:B1000>A30:A1000-1,A30:A1000))
Now the code works just fine.
With Worksheets("Sheet3")
.Range("A2").FormulaArray = .Range("b2").Formula
End With
Note that I could not test this using semi-colons as the system list separator; only with my own system's commas. VBA does not like anything by EN-US regional settings in a .Formula, .FormulaR1C1 or .FormulaArray property. If you still have trouble, use debug,print to see how the .Formula is being returned. If it contains semi-colons, then use,
With Worksheets("Sheet3")
.Range("A2").FormulaArray = Replace(.Range("b2").Formula, Chr(59), Chr(44))
End With

can not set a formula in specific cell

I trying to put a formula in my spreadsheet this formula works very well when i simply copy & paste in excel but when I try to create a macro for this some error occurs I cant understand what is the reason as it seems everything correct in my macro.
I am using below code-
Sub putformula()
range("K4").formula="=IF(ISBLANK($M4);"";IF($M4<=15;ABS($E4)*$K$3;""))"
range("L4").formula="=IF(ISBLANK($M4);"";IF($M4>31;"";IF($M4>15;ABS($E4)*$L$3;"")))"
range("M4").formula="=IF(OR($O4="ABS-Journal";$C4="ABS-Journal");"";IF(ISBLANK($D4);"";IF($C4=$O4;"";IF(MONTH($A4)=MONTH($M$3);IF(ISNUMBER(SEARCH("Invoice";$C4;1));$N4-$A4;$A4-$N4);""))))"
range("N4").formula="=IF(ISBLANK($B4);$N3;$A4)"
range("O4").formula="=IF(ISBLANK($B3);$O3;IF(ISBLANK($B3);"";$C4))"
End Sub
any suggestion will be appreciated.
Try this
Range("K4").Formula = "=IF(ISBLANK($M4),"" "",IF($M4<=15,ABS($E4)*$K$3,""""))"
You are also using ";" instead of "," .
The problem is you have to build a string and you were doing it wrong.
Try to understand and make the changes for every other range.