#Value! error when writing formula - excel

I have a piece of code that loops down a column and inserts a formula into each cell in that column. The code runs, the only problems is that each cell the formula is inserted into displays #Value! Does anyone know how to fix this?
Here is the piece of code with the problem:
Dim j As Long
'Loop down the rows in mainfile
For j = 2 To lastFullRow2
' Make each argument a string, then concatenate it all all into large string
Dim firstArgument As String
firstArgument = "ws_multidax.Range(" & valuecolumnLetter & "2:" & valuecolumnLetter & lastFullRow1 & ")"
Dim secondArgument As String
secondArgument = "ws_multidax.Range(" & parameter1columnLetter & "2:" & parameter1columnLetter & lastFullRow1 & ")"
Dim thirdArgument As String
thirdArgument = "ws_multidax.Range(" & parameter2columnLetter & "2:" & parameter2columnLetter & lastFullRow1 & ")"
Dim fourthArgument As String
fourthArgument = "ws_multidax.Range(" & parameter2columnLetter & "2:" & parameter2columnLetter & lastFullRow1 & ")"
Dim condition3 As String
condition3 = "ws_mainfile.Range(" & "D2:" & D & j & ")"
Dim patid1 As String
patid1 = "ws_multidax.Range(" & "D2:" & D & lastFullRow2 & ")"
With ws_mainfile
Dim commandstring As String
'The formula we want is a concatenated string
commandstring = "{=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))}"
'Insert the formula into each cell as the loop goes down the rows
ws_mainfile.Range("AN" & j).Formula = Eval(commandstring)
'ws_mainfile.Range("AN" & j).Formula = commandstring
End With
Next j
The #Value! gets put into the cells when I run the line with the Eval(commandstring). When I run the line with just formula = commandstring, the formula gets put in each cell, but it does not solve.

Your code has 2 problems:
You are putting in the curly braces of an array formula manually, don't do this
You are putting in an array formula as a regular formula
So to correct, do the following:
'1. Change this line:
commandstring = "{=INDEX(....)}"
'And simply remove the curly braces {} from its beginning and end
commandstring = "=INDEX(....)"
'2. Change this line:
ws_mainfile.Range("AN" & j).Formula = Eval(commandstring)
'To use the .FormulaArray property instead of just .Formula:
ws_mainfile.Range("AN" & j).FormulaArray = commandstring

You're on the right track. There's no need to use the eval function, as you have built a string formula in code. The problem is you have surrounded it with the braces, which excel treats as if you had entered text.
Try this instead:
commandstring = "=INDEX(" & firstArgument & ",MATCH(1,(" & secondArgument & "=" & condition1 & ")*(" & thirdArgument & "=" & condition2 & ")*(" & patid1 & "=" & condition3 & "),0))"
'Insert the formula into each cell as the loop goes down the rows
ws_mainfile.Range("AN" & j).Formula = commandstring

Related

VBA using part of formula as a celll value

Failing againg with my project
I have formulas with variable Brand that is changed dynamically (AF Column). Basically all I want is to extract Brands into a column next (AE) to the formula column for visial convenience
For i = LBound(Brand) To UBound(Brand)
Range("AF" & i + 2).Formula = "=COUNTIFS(C:C," & RTrim(Month(Mesyaz3)) & _
",H:H,""Headphones"",F:F," & Chr(34) & Brand(i) & Chr(34) & ")"
Next i
Range("AF:AF").Sort Key1:=Range("AF2"), Order1:=xlDescending, Header:=xlYes
ActiveSheet.Range("AG2:AG8").Formula = ActiveSheet.Range("AF2:AF8").Formula
ActiveSheet.Range("AH2:AH8").Formula = ActiveSheet.Range("AF2:AF8").Formula
Dim ws As Worksheet
Set ws = Worksheets(1)
Dim j As Variant
j = Application.Match(""" & Brand(i) & """, ws.Range("AF2:AF8"))
ActiveSheet.Range("AE2").Value = Application.Index(ws.Range("AF2:AF8"), j, 0)
And I get #N/A Already lost two days for that. Would be enourmously grateful to anyone who could help.
It's not exactly clear from your question as to your desired output but here's a guess:
For i = LBound(Brand) To UBound(Brand)
Range("AF" & i + 2).Formula = "=COUNTIFS(C:C," & RTrim(Month(Mesyaz3)) & _
",H:H,""Headphones"",F:F," & Chr(34) & Brand(i) & Chr(34) & ")"
Range("AE" & i + 2).Value = Brand(i)
Next i
Range("AE:AF").Sort Key1:=Range("AF2"), Order1:=xlDescending, Header:=xlYes
I've added a line to write the brand to AE, and altered the Sort to accommodate this.

Insert Formula with Variable in VBA

I'm trying to use a variable into formula using VBA. I've referenced How to pass an integer variable into a vba formula this question and tried implementing that in my if formula.
=IF (startCell >0, startcell+confirmed, endcell+confirmed)
but I'm still unsure and getting an error.
My code is the following:
headerrow = 7
startCell = 8
endCell = 3
confirmed= 5
DDSS_Actual.Cells(headerrow + 3, 3).Formula = "=IF(" & startCell & ">" & endCell & ","& startCell & "+" &confirmed&", " & endCell & "+" &confirmed &")"
Thanks.
You just need to put spaces before and after the &
which makes it
DDSS_Actual.Cells(headerrow + 3, 3).Formula = "=IF(" & startCell & ">" & endCell & "," & startCell & "+" & confirmed & "," & endCell & "+" & confirmed & ")"

Adding formula to a cell and referencing to variables

I am trying to get a formula into a cell with variables from VBA, but I'm getting another Application or Object defined error. The error is triggered on the first row op Range("R" & i).FormulaR1C1 = "=Q" & i & "/" & DollarRate. I have tried using just Formula instead of FormulaR1C1.
Columns Q and R are empty. Column Q will contain values in € and Column R will show the value in $.
Dim LastRow As Integer, i As Integer
Dim DollarRate As Double
DollarRate = InputBox("Enter dollar rate:", "Dollar rate")
Range("Q1").Value = "$ POS"
Range("R1").Value = "€ POS"
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
Range("R" & i).FormulaR1C1 = "=Q" & i & "/" & DollarRate
Next i
Try replacing this:
For i = 2 To LastRow
Range("R" & i).FormulaR1C1 = "=Q" & i & "/" & DollarRate
Next i
with this:
Range("R2:R" & lastrow).FormulaLocal = "=Q2/" & DollarRate

Unable to get the Match Property of the WorksheetFunction class error

I have a whole bunch of data on a whole bunch of sheets and for each of them, I want to find the count of the unique values in a given column.
When I use the following command in a sheeet, it works perfectly
=SUM(IF(FREQUENCY(MATCH(REST!D2:D2225,REST!D2:D2225,0),MATCH(REST!D2:D2225,REST!D2:D2225,0))>0,1))
But when I use an equivalent command inside VBA, I am getting errors
range1 = Cell(2,j).Address & ":" & Cells(k,j).Address
= Application.WorksheetFunction.SUM( Application.WorksheetFunction.IF( Application.WorksheetFunction.FREQUENCY( Application.WorksheetFunction.MATCH(Range(range1),Range(range1),0), Application.WorksheetFunction.MATCH(Range(range1),Range(range1),0))>0,1))
I have tried other combinations, like using
Application.Match
and
Application.Frequency
I've also got "type mismatch errors.
On the other hand, the following function works perfectly
Application.Worksheetfunction.Sum(Range(range2))
The big difference between range1 and range2 is that range2 data is strictly numeric while range1 data is both numeric and string.
EDIT: TO implement BX201's solution
range_TradeID_total_FL = .Cells(2, TradeId_column).Address & ":" & Cells(Finalrow, TradeId_column).Address
doubleQ = Chr(34) & Chr(34)
fStr = "=SUMPRODUCT((range_TradeID_total_FL & " <> " & " & doubleQ & ")/COUNTIF(range_TradeID_total_FL , range_TradeID_total_FL & " & " & " & doubleQ & "))"
var_TOTAL_TradeId_count_FL = Evaluate(fStr)
MsgBox var_TOTAL_TradeId_count_FL
I don't want to store the values in a cell but store it in a variable. But when I do that, the MsgBox gives me the value "True" instead of a number.
#SiddharthRout I am not aware of evaluate. Can you please tell me how it would work in my context, especially when I use variables for range.
Try this (UNTESTED)
This is an example where row is a variable.
Sub Sample()
Dim r1 As Long, r2 As Long
Dim formulaString As String
r1 = 2
r2 = 2225
'=SUM(IF(FREQUENCY(MATCH(REST!D2:D2225,REST!D2:D2225,0),MATCH(REST!D2:D2225,REST!D2:D2225,0))>0,1))
formulaString = "=SUM(IF(FREQUENCY(MATCH(REST!D" & r1 & _
":D" & r2 & _
",REST!D" & r1 & _
":D" & r2 & _
",0),MATCH(REST!D" & r1 & _
":D" & r2 & _
",REST!D" & r1 & _
":D" & r2 & _
",0))>0,1))"
Debug.Print Application.Evaluate(formulaString)
End Sub
A much simpler formula for getting count of unique values in a column is:
=SUMPRODUCT((REST!$D$2:$D$2225<>"")/COUNTIF(REST!$D$2:$D$2225,REST!$D$2:$D$2225&""))
Normal formula so no need to CSE. This works best if there are no conditions attached to your values, like maybe a simple list of names or values.
I think evaluating this should give you the result you want. You can also assign it as a formula to a cell. Either of the following two approaches works, in that regard.
Insert formula into cell
Sub UniqueCount1()
doubleQ = Chr(34) & Chr(34)
fStr = "=SUMPRODUCT((REST!D2:D2225<>" & doubleQ & ")/COUNTIF(REST!D2:D2225,REST!D2:D2225&" & doubleQ & "))"
Range("C1").Formula = fStr
End Sub
Evaluate the formula and insert result into cell
Sub UniqueCount2()
doubleQ = Chr(34) & Chr(34)
fStr = "=SUMPRODUCT((REST!D2:D2225<>" & doubleQ & ")/COUNTIF(REST!D2:D2225,REST!D2:D2225&" & doubleQ & "))"
Range("C1").Value = Evaluate(fStr)
End Sub
A third one approach is to use a scripting dictionary. This is a bit more complicated, but it's pretty fast and can be used in a myriad of ways.
Sub UniqueDict()
Dim oDict As Object
Dim sElem As Variant, sList As Variant
sList = ThisWorkbook.Sheets("REST").Range("D2:D2225").Value
Set oDict = CreateObject("Scripting.Dictionary")
With oDict
For Each sElem in sList
If Not .Exists(sElem) And Not IsEmpty(sElem) Then
.Add sElem, Empty
End If
Next sElem
End With
MsgBox oDict.Count
End Sub
Hope this helps.
EDIT:
Here's an approach using your variables.
startRow = 2 'Or whatever it is based on your other code.
finalRow = 2225 'Or whatever it is based on your other code.
rngStr = "REST!$D$" & Startrow & ":$D$" & Finalrow '$D$2:$D$2225
dQ = Chr(34) & Chr(34) 'Double quote string.
fStr1 = "=SUMPRODUCT((" & rngStr & "<>" & dQ & ")" '=SUMPRODUCT((REST!$D$2:$D$2225<>"")
fStr2 = "/COUNTIF(" & rngStr & "," & rngStr & "&" & dQ & "))" '/COUNTIF($D$2:$D$2225,$D$2:$D$2225&""))
fStr = fStr1 & fStr2 '=SUMPRODUCT((REST!$D$2:$D$2225<>"")/COUNTIF($D$2:$D$2225,$D$2:$D$2225&""))
var_Total = Application.Evaluate(fStr)
MsgBox var_Total
Hope this helps.

VBA: Using & inside of an equation

I want to make a formula with a & inside it but VBA thinks its a concatenate symbol
""&"" does not work, are there any other tricks?
My formula:
Sheets("Elasticity").Cells(iRow, 38).Formula = "=SUMIFS(" & "All_Models!$W$2:$W$" & nrow & ",All_Models!$G$2:$G$" _ & nrow & ",Elasticity!L" & iRow & ",All_Models!$AL$2:$AL$" & nrow & ",Elasticity!AK" & iRow & _ ",All_Models!$B$2:$B$" & nrow & "," & "" <= "" & "&" & "ElasticityA" & iRow & ")"
I want to transform:
"" <= "" & "&" & "Elasticity!A" & iRow & ")"
into:
"<="&Elasticity!A2)
How about just this:
dim s as string
s = "my_complicated_formula" & "&" & "and_another_formula"
...All_Models!$B$2:$B$" & nrow & ",""<=""&" & "Elasticity!A" & iRow & ")"
s="foo" & Chr(38) & "bar"
Where chr(38) = &

Resources