VBA - Formula Array doe - excel

I tried to use .FormulaArray to get the smallest value in a column, but unfortunatly it does not work.
This is my code for the formula:
Worksheets("Test Sim").Range("B9").FormulaArray = "{=MIN(IF(B2:B8>0;B2:B8;""""))}"
If i write it without the curly braces runtime error 1004 appears, if i write it with them my table looks like this:
As you can see in B9 it will not show the number 9. what do i have to change that this will work?

You don't need the {} and when entering formulas via code you need to use the "US-style" comma separator.
Worksheets("Test Sim").Range("B9").FormulaArray = "=MIN(IF(B2:B8>0,B2:B8,""""))"

Related

Count number of numbers in a single cell

I want to count the number of numbers in a single cell.
Example:
In cell A1, I have the following addition:
=12+45+23+51+10 which totals (and shows) 141.
In cell B1, I would like the see how many numbers have been added together, which means that there should be 5 (12 is a number, 45 another one, etc... and all together, there are 5 numbers in cell A1).
I know it seems to be a ridiculous question, but I scanned all the platforms for this issue and did not find any suitable solution. Tried all the LEN and LEN SUBSTITUTE alternatives out there, but somehow it does not work.
Thank you upfront for your help. Optimal solution would be a excel formula, alternatively VBA would also work.
Excel 2013 has a new function Formulatext() which returns the, well, formula text. Using that the Len() and Substitute() approach works.
=LEN(FORMULATEXT(A1))-LEN(SUBSTITUTE(FORMULATEXT(A1),"+",""))+1
Hit Alt+F11 and Insert->Module with the following VBA:
Function NumCount(Rng As Range)
x = Split(Rng.Formula, "+")
NumCount = UBound(x) + 1
End Function
Then you can call =NumCount(A1) on any cell to get the number of numbers in the formula for that cell.
Use this VBA:
Function GetFormula(Cell as Range) as String
GetFormula = Cell.Formula
End Function
and then to get the number of numbers...
=LEN(GetFormula(D99))-LEN(SUBSTITUTE(GetFormula(D99),"+",""))
on this as my D99 contents...
=45+46+47+50+100
The one major drawback here is that I'm assuming everything is + if you have -, *,/ or other operators this gets more challenging. you might be able to use replace for each but you'd always be limited to the 4 basic operators... if someone used exponents or mod, this would be harder.
Also possible in earlier Excel versions without VBA - subject to (i) there is always at least one value in the cells, (ii) the operator is always + and (iii) the cells are in a column.
Replace = with '= in that column, apply the substitution, say:
=LEN(A1)-LEN(SUBSTITUTE(A1,"+",""))+1
in a different column and Paste Special, Value the results for that other column. Then apply Text To Columns on the original column with ' as the delimiter.
*There is no way to do this without using a User Defined Function (UDF) written in Excel VBA. Something like this should work:
Public Function numsAdded(cell1 As Range)
Dim formulaString As String
formulaString = cell1.Formula
numsAdded = Len(formulaString) - Len(Replace(formulaString, "+", "")) + 1
End Function
Once you've added that to a VBA module, you can use it as a function in any cell in your spreadsheet.
*Edit - Apparently there is a way if you have Excel 2013, as teylyn suggests. If you use 2010 or earlier like me, you'll need VBA.
Try this:
=LEN(SUBSTITUTE(F16,"+","+"))
Note: F16 is only an example name for the cell you want to do the counting on.
Example:
F16=45+65+76 # Gives 186
F17=LEN(SUBSTITUTE(F16,"+","+")) # Gives 3

DataValidation, strange error

I am trying to validate an Excel column to have only values containing a value with length > 1 and ending with "d".
My attempt was the following formula:
=AND(LEN(INDIRECT(ADDRESS(ROW(),COLUMN())))>1,RIGHT(INDIRECT(ADDRESS(ROW(),COLUMN())),1) = "d")
Excel says that the formula contains errors.
The strange thing is that the first part itself works correct. But when i put it into an AND i get the error. Also when i replace the inderect reference with an absolut one it will work:
=LEN(INDIRECT(ADDRESS(ROW(),COLUMN())))>1 => works
=AND(LEN(F4)>1, TRUE) => works
=AND(LEN(INDIRECT(ADDRESS(ROW(),COLUMN())))>1, TRUE) => fails
Why is this? Is there another way or a workaround to do this?
Thanks in advance, Marco
Not sure why you need this to be so complicated. In data/validation Custom formula for the top cell in the column, put something like =AND(LEN(H1)>1,RIGHT(H1,1)="d") (for col H, for example). Then Copy that cell, and Paste Special/Validation for the rest of the cells in the column. Any good?

In Excel and VBA, how to set value of cell to the formulas result rather than the formula

I'm getting values from one sheet and placing them in another using a macro in Excel. I currently have this which works fine:
sheet.range("B2:B35").Value = "=IF(SUMPRODUCT(--(Raw!$B$11:$B$322=$A2),--(Raw!$D$11:$D$322=All!$B$2),Raw!$H$11:$H$322)<>0,SUMPRODUCT(--(Raw!$B$11:$B$322=$A2),--(Raw!$D$11:$D$322=All!$B$2),Raw!$H$11:$H$322),""-"")"
It, obviously, puts that entire formula as the value of the cell. What I'd like is it just to put the result of the formula into the cell. I've tried adding Evaluate() around the "IF..." part, but then the IF doesn't evaluate correctly (I just end up with "-" in each cell). Is this possible to do or do I have to have separate code to loop through and change the value to the value of the cell?
Use:
sheet.range("B2:B35").Formula = "Your formula here"
If that doesn't work you may have to change the formatting (do this first):
sheet.range("B2:B35").NumberFormat = "General"
Edit:
A solution turned out to be addition of the following line after the OP's code:
sheet.range("B2:B35").value = sheet.range("B2:B35").value

Manual Record Excel Macro error - insert formula into a cell

I was trying to insert a formula directly into a cell and have it reference the cells around it based on where it is placed (R1C1). I turned on the record macro feature in excel and edited a cell with the desired formula and hit enter. Excel provided me with the following function. The odd part about this, is this is the exact formula excel gave me, and when I try to run the function, it errors out with a "run time error '1004': Application-defined or object defined error.
Background on the use: The function itself is just for a budget I am creating and it uses a cell two columns over to decide whether to continue numbering or to create a subset of the number above (TR is notation for total request, so anything that is not a TR, is a subset of the total request, and will be labeled the last known number & 'A', 'B', etc)
ActiveCell.FormulaR1C1 = _
"=IF(RC[2]=""TR"",IF(R[-1]C[2]<>""TR"",IF(R[-2]C[2]<>""TR"",IF(R[-3]C[2]<>""TR"",IF(R[-4]C[2]<>""TR"",IF(R[-5]C[2]<>""TR"",IF(R[-6]C[2]<>""TR"",IF(R[-7]C[2]<>""TR"",""add more"",R[-7]C+1),R[-6]C+1),R[-5]C+1),R[-4]C+1),R[-3]C+1),R[-2]C+1),R[-1]C+1), IF(R[-1]C[2]=""TR"",IF(RC[2]<>""TR"",R[-1]C&""A"",R[-1]C+1),IF(R[-2]C[2]=""TR"",R[-2]C&""B"",IF(R[-3]C[2]=""TR"",R[-3]C&" & "(R[-4]C[2]=""TR"",R[-4]C&""D"",IF(R[-5]C[2]=""TR"",R[-5]C&""E"",IF(R[-6]C[2]=""TR"",R[-6]C&""F"",IF(R[-7]C[2]=""TR"",R[-7]C&""G"",""""))))))))"
Any help on this will be appreciated,
thanks
Edit:
I'm at work, and I cant respond in line, so I decided to try here: Below is the recorded macro as is.
Sub Macro7()
'
' Macro7 Macro
'
'
ActiveCell.FormulaR1C1 = _
"=IF(RC[2]="""","""",IF(RC[2]=""TR"",IF(R[-1]C[2]<>""TR"",IF(R[-2]C[2]<>""TR"",IF(R[-3]C[2]<>""TR"",IF(R[-4]C[2]<>""TR"",IF(R[-5]C[2]<>""TR"",IF(R[-6]C[2]<>""TR"",IF(R[-7]C[2]<>""TR"",""add more"",R[-7]C+1),R[-6]C+1),R[-5]C+1),R[-4]C+1),R[-3]C+1),R[-2]C+1),R[-1]C+1), IF(R[-1]C[2]=""TR"",IF(RC[2]<>""TR"",R[-1]C&""A"",R[-1]C+1),IF(R[-2]C[2]=""TR"",R[-2]C&""B"",IF(R[-3]" & _
"R"",R[-3]C&""C"",IF(R[-4]C[2]=""TR"",R[-4]C&""D"",IF(R[-5]C[2]=""TR"",R[-5]C&""E"",IF(R[-6]C[2]=""TR"",R[-6]C&""F"",IF(R[-7]C[2]=""TR"",R[-7]C&""G"","""")))))))))"
Range("C121").Select
End Sub
This is the recorded macro from the record macro feature.
The formula was designed in excel, and i'm attempting to reuse it inside a macro. the reason I didn't try a select case or anything like that is because this formula was designed to dynamically change based the cells around it. So if i add a line above it and insert a new budget line (this is for a budget as referenced above), the lines below it will change accordingly.
edit:ex of what it looks like in excel:
You have an error in the formula, that's why VBA isn't adding the formula.
I've pulled out the formula and tried to put it in manually and excel throws a message saying there is an error.
With all the to and fro on possible errors in the formula, it's clearly too unwieldy to debug easily, so here's an alternative:
=COUNTIF(E$16:E128,"TR")&IF(E128="TR","",IF(E127="TR","A",CHAR(CODE(MID(C127,2,1))+1)))
or in R1C1 format
=COUNTIF(R16C[2]:RC[2],"TR")&IF(RC[2]="TR","",IF(R[-1]C[2]="TR","A",CHAR(CODE(MID(R[-1]C,2,1))+1)))
And VBA code to add it to the Active Cell
ActiveCell.FormulaR1C1 = _
"=COUNTIF(R2C[2]:RC[2],""TR"")& _
IF(RC[2]=""TR"","""",IF(R[-1]C[2]=""TR"",""A"",CHAR(CODE(MID(R[-1]C,2,1))+1)))"
It has the added benifit of not being limited to 7 levels (well, in practice limited to 26 levels, after which it will append some odd characters)
Note: the first cell reference R2C[2] may need to be adjusted to match the starting row of your data, eg if the first rank is in row 128 change it to R128C[2]
How it works:
Count the number of TR's in the table down to this row.
If the Type column is TR, return this count
Otherwise, if the Type in the row above is TR, append A
Otherwise, get the character off the end of the Rank in the row above, increment it to the next character and append it
Note: If the first Type is not TR you will get unexpected results down to the first TR

Excel macro formula adding quotes in formula causing vlookup to not work

I am trying to add a formula to a cell. The macro is adding quotations around the cell range, which causes the cell to return the #name error.
This is the code in the macro
Cells(1, 4).FormulaR1C1 = "=VLOOKUP(RC[-2],Contracts!A7:D30,3,FALSE)"
This is what the code returns in Excel after executing the macro.
=VLOOKUP(B4,Contracts!'A7':'D30',3,FALSE)
Note that #name error disappears and the formula works, after I remove the quotations around the cell A7 and D30.
You cannot mix RC and A1 style references in the same formula. Pick one and stick to it.
"=VLOOKUP(RC[-2],Contracts!R7C1:R30C4,3,FALSE)"
will work
The RC[-2] seems to be the problem. When I replaced that with a normal cell reference the macro didn't put quotes around the A7 and D30.
I believe the problem is caused by mixing RC notation (FormulaR1C1) and A1. Have you tried:
Cells(1, 4).FormulaR1C1 = "=VLOOKUP(RC[-2],""Contracts!A7:D30"",3,FALSE)"
? That should work.

Resources