VBA SumProduct Runtime Error 13 - vba

As a part of a much longer code, I am trying to include a SumProduct
Dim SumPr as Variant
SumPr=Application.WorksheetFunction.SumProduct(((Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("A:A")) = Range("A" & i)) * ((Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("D:D")) = "PH") * (Workbooks(Source2).Sheets("Prices_EUR_Adj").Range(ColLtr & ":" & ColLtr)))
MsgBox SumPr
However, I keep getting Runtime Error 13 for some reason. Any idea what is wrong? Source2 is properly defined, and ColLtr is letter conversion of column number I got from match; it also works ok as checked by message box.

Try using the Evaluate function instead:
Dim SumPr As Variant
SumPr = Application.Evaluate("SUMPRODUCT(--(" & Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("A:A").Address & "=" & Range("A" & i).Address & ")," & _
"--(" & Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("D:D").Address & "=""PH"")," & _
Workbooks(Source2).Sheets("Prices_EUR_Adj").Range(ColLtr & ":" & ColLtr).Address & ")")
MsgBox SumPr
I'm sure the WorksheetFunction.SumProduct will also work, but I was able to get the Evaluate function working easier.

Related

Apply Conditional Formatting Expression with VBA

I am trying to make a conditional format for cell rC. If the sum of absolute values in a range is different from zero, it should trigger the condition.
The Conditional Formatting Expression works in worksheet.
The actual content of sB is more complicated, but I get the same error when trying the simple code below.
( ; as I am on a Danish configuration):
sA = "ADDRESS(" & rC.Row & "+1;" & rC.Column & ";4)"
sB = "ADDRESS(" & rC.Row & "+2;" & rC.Column & ";4)"
rC.FormatConditions.Add Type:=xlExpression, _
Formula1:="=sum(abs(indirect(" & sA & ")" & ":" & "indirect(" & sB & ")))<>0"
It returns
Run-time error '5': Invalid procedure call or argument
Stepping into the code the formula returns
"=sum(abs(indirect(ADDRESS(4+1;8;4)):indirect(ADDRESS(4+2;8;4))))<>0", which works [returns false] when pasted into the spreadsheet.
Maybe it's possible to avoid both sA and sB completely, i.e.
rC.FormatConditions.Add Type:=xlExpression, Formula1:="=SUM(ABS(" & rc.Offset(1, 0).Address(False, False, xlA1) & ":" & rc.Offset(2, 0).Address(False, False, xlA1) & "))<>0"

Can VBA attempt to assign to a cell a formula that is too long?

I am on Windows, if that matters. This code seems to attempt to assign a formula that is too long:
ActiveSheet.ListObjects("SegmentValues_1").ListColumns("Change").DataBodyRange.Formula = "=IFERROR(IF(INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([#Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0))=0,""Last total was ZERO"",([#CODE_ZONE]-INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([#Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0)))/INDEX(SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[CODE_ZONE],MATCH([#Modules],SegmentValues_" & (ActiveWorkbook.Sheets.count - 2) & "[Modules],0)))),""Did not exist previously"")"
Is such a thing possible? If so, how to solve it?
The long formulas work in Excel VBA quite well. Take a look at this 24 nested IF():
Sub TestMe()
Range("A1").Formula = "=IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
"IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
"IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
"IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
"IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1,IF(1=1," & _
"IF(1=1,2))))))))))))))))))))))))))))))))))))))))))))))"
End Sub
It is translated really well into Excel. Thus, take a good look at your formula, the problem should be there.

Excel VBA - insert formula in a set of rows with variable reference directly or replacing a string for example "\=" with "="

I have the goal to write a formula in a set of rows. Some references in the formula have to change each row.
I implemented the following script:
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 0 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."";A" & i & ";IF(Q" & i & "=""Ist"";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=""Lz."";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=""Ist+Lz.-Bedarf"";OFFSET(A" & i & ";-3;0);)))))"
Let temprng = "M" & i
Range(temprng).Select
ActiveCell.Value = "\=" & formcolM
next i
With this script I am writing a string each row in my excel table at column M.
I noticed that if the formula hasn't the symbol "\" , you can find an error .
In order to avoid the error I thought to leave the symbol "\" and to use a trick deleting it after (because I don't know how to solve with R1C1 formula. I read some answers on Stackoverflow, but unfortunately I did not understand )
The replacing script after the for cycle:
Columns("M:M").Replace What:="\=", Replacement:="=", LookAt:=xlPart
The strange thing is that the macro doesn't delete it.
Infact when the script finishes , it seems that nothing happened, without errors. But if I want substitute "\=" with another symbol, for example "*", the replacing script works.
I did not understand if the problem is :
the replace method did not recognized the symbol "=" to search
I cannot use the replace method because the symbol "=" disturbs in some way , I don't know in what.
OR, is there another simplest way to get this task done?
Someone could help me in order to fix? I should have the formula working in the column M , automatically with vba (not with another formula in the excel sheet) .
Thanks in advance for your time.
We can apply the formula directly. The issue is that vba is very US-EN Centric and all formula when using the .Formula needs to be in that format.
Also since your formula refers to values in a row 3 above the one in which it is put we need to start the loop at 4 not 0. There is no row 0
There are two ways, in US-En format with English functions and , as the deliminator using .Formula:
Dim i As Integer
For i = 4 To 100
Range("M" & i).Formula = "=NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."",A" & i & ",IF(Q" & i & "=""Ist"",OFFSET(A" & i & ",-1,0),IF(Q" & i & "=""Lz."",OFFSET(A" & i & ",-2,0),IF(Q" & i & "=""Ist+Lz.-Bedarf"",OFFSET(A" & i & ",-3,0),)))))"
Next i
Or using .FormulaLocal and the formula as you would write it in your native tongue.
Dim i As Integer
For i = 4 To 100
Range("M" & i).FormulaLocal = "=NUMERO.VALORE(SE(Q" & i & "=""Bedarf kum."";A" & i & ";SE(Q" & i & "=""Ist"";SCARTO(A" & i & ";-1;0);SE(Q" & i & "=""Lz."";SCARTO(A" & i & ";-2;0);SE(Q" & i & "=""Ist+Lz.-Bedarf"";SCARTO(A" & i & ";-3;0);)))))"
Next i
By the time I got this worked out, Scott already had an answer. I just wanted to post your original code modified to work. I would suggest his method.
Sub TestScript()
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 4 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=" & "Bedarf kum." & ";A" & i & ";IF(Q" & i & "=" & "Ist" & ";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=" & "Lz." & ";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=" & "Ist+Lz.-Bedarf" & ";OFFSET(A" & i & ";-3;0);)))))"
temprng = "M" & i
Sheets("Sheet1").Range(temprng).Select
ActiveCell.Value = " = " & formcolM
Next i
End Sub

VBA -- variable in .formula

is there a more elegant (simpler) way to put a variable in .formula? I don't want to use .formulaR1C1
I have this code:
Range("C8").Select
Selection.End(xlDown).Select
PosR = ActiveCell.Row
KonR = PosR - 2
Range("N" & PosR).Select
aAddress = Range("$N$9").Address & ":" & Range("$N$" & KonR).Address
ActiveCell.Formula = "=SUM(" & aAddress & ")"
Obviously I want to put =SUM($N$9:$N$101) (101 is the last cell minus 2) into that cell and this code does the job. But I just want to be sure that this is the easiest way to do this.
The easiest way is to skip all that selecting and those variables
PosR = Range("C8").End(xlDown).Row
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
Edit: to be more explicit, the easiest way is to use FormulaR1C1 but you said you didn't want to, so...
You can use the code below (without using Select and ActiveCell:
PosR = Range("C8").End(xlDown).Row
KonR = PosR - 2
Range("N" & PosR).Formula = "=SUM(" & Range("$N$9").Address & ":" & Range("$N$" & KonR).Address & ")"
Or, the much simplier version:
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & KonR & ")"
Well you should be trying to avoid using Select in VBA. You've made the actual inclusion of a variable in the .Formula about a simple as it gets, but your whole code could be simplified:
PosR = Range("C8").End(xlDown).Row
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
Really you should be fully qualifying your ranges too, like so
With ThisWorkbook.Sheets("Sheet1")
PosR = .Range("C8").End(xlDown).Row
.Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
End With
And if you have blank cells in column C then your use of xlDown will fail to find the last cell. You may want to look at ways of finding the last cell in VBA or simply use
' Again, preferably fully qualified
Range("C" & Rows.Count).End(xlUp).Row
Range("$N$9").Address gives exactly "$N$9".
Range("N9").Address gives the same. Thus, it is a bit overwork. Check out the first two debug.print in the sample below.
Thus, once you calculate the last row and assign value to it lngLast, it is possible to get the formula like this:
"=SUM(N9:N" & lngLast & ")"
Option Explicit
Public Sub TestMe()
Dim strA As String
Dim lngLast As Long
strA = Range("$N$9").Address
Debug.Print strA = "$N$9"
strA = Range("N9").Address
Debug.Print strA = "$N$9"
lngLast = Range("N" & Rows.Count).End(xlUp).Row - 2
ActiveCell.Formula = "=SUM(N9:N" & lngLast & ")"
End Sub
Good morning, everyone :)

SUMIFS function from other workbook - Error is Type Mismatch

I would like to do SUMIFS function in a range of active sheet from other workbook. Here is where I get my error of Macro:
ActiveSheet.Range(ActiveSheet.Cells(6, lastCol + 1),
ActiveSheet.Cells(lastRow, lastCol + 1)).Formula = Application.WorksheetFunction.SumIfs(" ' " & wbGSD.Name & "'!$F$10:$F$" & wbGSDlastRow & ",'" & wbGSD.Name & "'!$B$10:$B$" & wbGSDlastRow & ",B6,'" & wbGSD.Name & "'!$C$10:$C$" & wbGSDlastRow & ", Total")
The error I got is:
Type Mismatch
I tried Sumif function. It didn't work either.
You're passing SumIfs() one long string. It doesn't take one long string. It takes a number of parameters, the first two of which are Range objects, not strings. If you want to write your formula as one long string, then there's no need for WorksheetFunction.SumIfs(). Just assign the string formula to the range's Formula property:
Range("A1").Formula = "=SUMIFS('" & wbGSD.Name & "'!$F$10:$F$" & ...
If you really do want to use WorksheetFunction.SumIfs(), you'll need to use it properly by passing individual parameters of the right type:
Range("A1") = WorksheetFunction.SumIfs( _
Sheets(wbGSD.Name).Range("$F$10:$F$" & wbGSDlastRow), _
Sheets(wbGSD.Name).Range("$B$10:$B$" & wbGSDlastRow), _
....