sumproduct Formula array in VBA - excel

ActiveSheet.Evaluate("=SUMPRODUCT((""" & Source1_Val & """ = " & Target1 & ")*(""" & Source2_Val & """ = " & target2 & ")*ROW(" & Target1 & "))")
The same formula works when I directly put in Excel but when done throught VBA I am not getting any result.
Excel formula:
=SUMPRODUCT((Source!Q2=Q1:Q33)*(Source!L2 = L1:L33)*ROW(L1:L33))

Are you looking for MSDN -Using Ranges?
Range("AD:AD").Select
Range("AE:AE").Select

Are Column1, etc., all defined names? Then:
.Evaluate("=SUMPRODUCT((Column1=Source1_Val)*(Column2=Source2_Val)*ROW())")

The answer is pretty dumb. Remove the = sign from the text.
Assume that the cell D7:D9 as well as E7:E9 contains numeric values, the following function works well in the immediate window
?Evaluate("SUMPRODUCT(D7:D9, E7:E9)")
EDIT: With the assumption that all the variables names below are string.
dim myFormula as string
myFormula = "SUMPRODUCT((" & Source1_Val & " = " & Target1 & ")" _
& " * (" & Source2_Val _
& " = " & target2 & ")*ROW(" & Target1 & "))"
ActiveSheet.Evaluate(myFormula)
There is no need to include extra double-quotes in the formula.
EDIT2: Based on the attached file, here is the code to show that it works
option explicit
Sub TestFormulaStringUsingEvaluate()
Dim formula As String
Dim source1_Val As String
Dim source2_Val As String
Dim target1 As String
Dim target2 As String
'** Fill in the values for the following 4 variables
source1_Val = "Source!Q2"
target1 = "Target!Q$1:Q$10"
source2_Val = "Source!L2"
target2 = "Target!L$1:L$10"
formula = "SUMPRODUCT((" & source1_Val & "= " & target1 & ") " _
& "*(" & source2_Val & "=" & target2 & ") " _
& "* ROW(" & target2 & "))"
MsgBox Application.Evaluate(formula)
End Sub

Related

Printing the output of a macro directly on cell A1 rather than displaying on the msgbox [duplicate]

This question already has an answer here:
Passing variables using excel macros in order to complete a sentence
(1 answer)
Closed 5 years ago.
I want to print the below output in my excel sheet rather than displaying on the msg box.
I have written the below code but I am not able to print the output of sCommand in my excel sheet.
I want to print the output on cell A1.
Thanks in advance.
sCommand = "Call " & s1 & "." & s2 & "(" & "'" & INPUT_DATE & "'" & "," & "'" &EXIT_DATE & "'" & "," & "STATUS " & ")" & ";"
MsgBox (sCommand)
Same as Gadziu, but instead of using .Cells(1,1) using .Range:
sCommand = "Call " & s1 & "." & s2 & "(" & "'" & INPUT_DATE & "'" & "," & "'" &EXIT_DATE & "'" & "," & "STATUS " & ")" & ";"
ActiveSheet.Range("A1").Value = sCommand
You should also declare which Sheet you are actually wanting to write to, as ActiveSheet will take the sheet that is currently selected/active, so this could be better defined as:
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
Dim s1 As String, s2 As String, sCommand As String
s1 = InputBox("Enter schema name")
s2 = InputBox("Enter procedure name")
Input_date = Format(Date, "dd/mm/yyyy") 'get today's date or: Input_date = InputBox("Enter Input Date")
Exit_Date = Format(Date, "dd/mm/yyyy") 'get today's date or: Exit_Date = InputBox("Enter Exit Date")
Status = InputBox("Status")
sCommand = "Call " & s1 & "." & s2 & "(" & "'" & Input_date & "'" & "," & "'" & Exit_Date & "'" & "," & Status & ")" & ";"
'concatenate your variables into a string
'ws.Cells(1, 1).Value = sCommand 'the Cells(1, 1) refer to Cells(row_number, column_number)
ws.Range("A1").Value = sCommand
End Sub
sCommand = "Call " & s1 & "." & s2 & "(" & "'" & INPUT_DATE & "'" & "," & "'" &EXIT_DATE & "'" & "," & "STATUS " & ")" & ";"
ActiveSheet.Cells(1,1).Value = sCommand

Getting ExecuteExcel4Macro to Recognise Empty Cells

When I use the ExecuteExcel4Macro function in a VBA script like so:
Public Function GetNamedData(Path, File, Address)
Dim Data As String
Data = "'" & Path & File & "'!" & Address
GetNamedData = ExecuteExcel4Macro(Data)
End Function
Where Address is a named range in my case, if the cell in the closed workbook is empty, this function returns 0. But some cells contain (deliberately) 0.
How do I differentiate between empty cells and cells containing 0?
To explain further, I am using this function to get data from a closed workbook. This has proven very fast at collecting lots of data from closed workbooks.
I understand there are differences between '0' and empty, but I am not sure how to work it into this function.
Try this one:
GetNamedData = ExecuteExcel4Macro("IF(COUNTA(" & Data & ")," & Data & ",""X"")")
Then GetNamedData = "X" in case the cell in closed workbook is empty.
The below function adds a "" (Null) the the value and so the GetValue2 function returns a null if empty or a zero if it is a zero.
Function GetValue2(strPath As String, strFilename As String, strTabName As String, intColumnNumber As Integer, intRowNumber As Integer) As String
Dim varCellValue As Variant
Dim strContents As String
On Error GoTo ErrHandler
varCellValue = ExecuteExcel4Macro("'" & strPath & "[" & strFilename & "]" & strTabName & "'!R" & intRowNumber & "C" & intColumnNumber & " & """"")
strContents = CStr(varCellValue)
GoTo NiceExit
ErrHandler:
Call MsgBox("strPathFilename : " & strPath & strFilename & Chr(13) & _
"strTabName : " & strTabName & Chr(13) & _
"intColumnNumber : " & intColumnNumber & Chr(13) & _
"") ' & Error.msg, vbOKOnly)
NiceExit:
GetValue2 = strContents
End Function

Escaping for Countif macro with wildcard cell reference

I cant for the life of me get the escapes working correctly for my macro. I am trying to input a Countif function that uses wildcards on either side of a cell reference value, it also finds the last row within a separate tab to help define the range to count in.
I want the target cell to contain the following string:
=COUNTIF('NCR''s'!$B$8:$C$117,"*"&'Design Baseline'!B8&"*")
The following is the code that attempts to do this:
Sub test()
Dim Wild1 As String
Dim Wild2 As String
Wild1 = Chr(34) & Chr(42) & Chr(34) & Chr(38)
Wild2 = Chr(38) & Chr(34) & Chr(42) & Chr(34)
'code for counting instances of parts on each tab
Sheets("NCR's").Select
Cells.Select
Selection.EntireRow.Hidden = False
NCRlastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Sheets("Design Baseline").Select
Cells.Select
Selection.EntireRow.Hidden = False
'Range("AB8").Formula = "=COUNTIF('NCR''s'!$B$8:$C$" & NCRlastRow & "," & Chr(34) & "*" & Chr(34) & "&" & "'Design Baseline'!B29" & "&" & Chr(34) & "*" & Chr(34) & ")"
Range("AB8").Formula = "=COUNTIF('NCR''s'!$B$8:$C$" & NCRlastRow & "," & Wild1 & "'Design Baseline'!B29" & Wild2 & ")"
End Sub
As you can see in the line beginning with ', I have tried to use the Chr(ref) method to get around this as well as using user defined strings for the ", * and & symbols. I have also attempted the double " escape and even ". Not sure how to get around this o.O
The following line was what I used before realizing I needed wildcards and worked fine, not sure if it would help but I'll put it here regardless:
Range("AC8").Formula = "=COUNTIF('NCR''s'!$B$8:$B$" & NCRlastRow & ",'Design Baseline'!B8)"
Any help would be greatly appreciated!
You need to escape the double quotes in your formula.
Something like this:
Dim formula As String
formula = "=COUNTIF('NCR''s'!$A$8:$C$" & NCRlastRow & ",""*"" &'Design Baseline'!B8&""*"")"
Debug.Print formula
Range("AB8").formula = formula

Paste excel formula (excel format) in a cell using excel VBA?

How do I insert or paste the large excel formula in a specific cell in excel formula formate only. My project has large excel table to calulate no. days left and it is linked with current date and time. formula has to be inserted in column whenever i submitted the data from data entry form. It automatically collects the values from different cells in a current sheet and calculates.
But here i getting "compile error, expected end of statement" at formula line ie., at double quatotions "".
I could write directly in excel and drage
or
I could write vba code for the above calculation but due to my project requirement, i have to be inserted the formula.
Is there any way to insert the formula???? i'm using excel 2016
Set Fcell = formulaWks.Range("O7")
'formula = "=$A1+$B1" ' example for testing
Formula = "=IF(YEAR(NOW())=$W$3,IF(ISBLANK($G7),"",IFERROR(IF(DATEDIF(TODAY(),$N7,"y")=0,"",DATEDIF(TODAY(),$N7,"y")&" y ")&IF(DATEDIF(TODAY(),$N7,"ym")=0,"",DATEDIF(TODAY(),$N7,"ym")&" m ")&IF(DATEDIF(TODAY(),$N7,"md")=0,"",DATEDIF(TODAY(),$N7,"md")&" d"),"wrong date")),"Package completed")"
Fcell = ActiveCell.formula
Try the code below, it will work with your basic formula that you wanted to test.
Option Explicit
Sub InsertFormula()
Dim formulaWks As Worksheet
Dim Fcell As Range
Dim FormulaString As String
' modify "Sheet1" to your sheet's name
Set formulaWks = Worksheets("Sheet1")
Set Fcell = formulaWks.Range("O7")
FormulaString = "=$A1+$B1" ' example for testing
Fcell.Formula = FormulaString
End Sub
Regarding your "LONG" formula, the formula string below passes:
FormulaString = "=IF(YEAR(NOW())=$W$3,IF(ISBLANK($G7)," & Chr(34) & Chr(34) & ",IFERROR(IF(DATEDIF(TODAY(),$N7," & Chr(34) & "y" & Chr(34) & ")=0," & Chr(34) & Chr(34) & ",DATEDIF(TODAY(),$N7," & Chr(34) & "y" & Chr(34) & ")&" & Chr(34) & " y " & Chr(34) & ")" & _
"&IF(DATEDIF(TODAY(),$N7," & Chr(34) & "ym" & Chr(34) & ")=0," & Chr(34) & Chr(34) & ",DATEDIF(TODAY(),$N7," & Chr(34) & "ym" & Chr(34) & ")&" & Chr(34) & " m " & Chr(34) & ")" & _
"&IF(DATEDIF(TODAY(),$N7," & Chr(34) & "md" & Chr(34) & ")=0," & Chr(34) & Chr(34) & ",DATEDIF(TODAY(),$N7," & Chr(34) & "md" & Chr(34) & ")&" & Chr(34) & " d" & Chr(34) & ")," & _
Chr(34) & "wrong date" & Chr(34) & "))," & Chr(34) & "Package completed" & Chr(34) & ")"
Debug.Print FormulaString ' for debug, to see the Formula string in the immediate window
Note: Final version of the "long" formula has been edited in by YowE3K - if it doesn't work, blame me (i.e. YowE3K) not Shai.
You need to escape double quotes from the string first by adding double quotes twice in the string like this - ISBLANK($G7),""""
Then use formula like this
Range("O7").Formula = "[Your formula with escaped double quotes]"

using symbol in vba to fill up cell

this is my code in vba excel
Range("a1").Value = "=" & Chr(34) & beat_name & Chr(34) & char(38)
final output
="name" & TEXT(TODAY(),"DD/MM/YYYY")
unable to show & sign in excel sheet
Consider:
Sub luxation()
s = "name "
Range("A1").Formula = "=" & Chr(34) & s & Chr(34) & " & TEXT(TODAY(),""DD/MM/YYYY"")"
End Sub

Resources