I'm trying to run the below code and it gives me
Run-Time Error "1004"
Application-defined or Object-defined error
Every Single Time!!
Attached is a snippet of the code, any suggestions what's wrong? (The numbers in the Range(Cells( * ) sections are actually mostly variables in my overall macro, it's pretty complex but I've taken them out for simplicity here)
Code:
'Declare variables
Dim CriteriaRng As String
Dim SumRng As String
Dim Criteria As String
'Set a variable for each of the 3 parts of the SUMIF Formula
CriteriaRng = "'" & Sheets(1).Name & "'!" & Range(Cells(2, 4), Cells(88, 4)).Address
SumRng = "'" & Sheets(1).Name & "'!" & Range(Cells(2, 3), Cells(88, 3)).Address
Criteria = Chr(34) & "=" & Chr(34) & " & RC[-1]"
'Here goes the SUMIF Formula
With Sheets(2).Range(Cells(4, 13), Cells(9, 13))
Debug.Print "So the Whole Formula Should be:" & Chr(13) & "= SUMIF(" & CriteriaRng & ", " & Criteria & ", " & SumRng & ")"
'That was a vain attempt to find out what was wrong with the formula; didn't work though.
.FormulaR1C1 = "= SUMIF(" & CriteriaRng & ", " & Criteria & "," & SumRng & ")"
'Then adds NumberFormat and stuff here, but that isn't relevant to this question.
End With
The error always hits on the line where it's putting in the .FormulaR1C1 = .
Yes, I know I could get the same result using a nested loop, but that would return just the value without the SUMIF formula - I need that formula so the sheet updates when edited (without needing a macro - I'm sending the sheet on to other people who won't have or want any macros, but might need to edit the data).
Can anyone point out to me what is wrong? I'm prepared for it to be something pretty basic - only last week I spent 2 hours figuring out a problem from misspelling 'Columns' !!!
Any and all advice welcome - Many Thanks in advance.
Related
I searched on internet, without any help coming out of that...
I simply would like to be able to have my VBA code to write this formula in a cell :
=IF(C4="-"; "-"; Cars!C4*C4*Data!$C$8)
As you guessed, there is a page called "Cars" and one called "Data" where I pick the informations needed.
Of course, as it is a VBA code, the C4 will be 2 variables, one for the C and one for the 4 that will evolve...
Actually, I tried this :
Worksheets("Calculation").Range(Column & PosStartCalc + 1).Formula = "=" & "IF(" & Column & PosStartCalc & " = " & "" - "" & ";" & " - " & ";" & "Cars!" & Column & PosStart & "*" & Column & PosStartCalc & "*" & "Data!" & "C" & "8" & ")"
(The variable Column contains the column letter and the variable PosStartCalc contains the row number)
This hurts my eyes and apparently VBA's ones too as it gives the error "Run-Time error '13': Type Mismatch'
Could anyone tell me how to do that?
Thanks in advance !
Try the following, assuming the column variable is a string and row a long variable. I might not have all the variables right, but you'll be able to get what I meant to do here.
Sub test()
Dim Col As String: Col = "C"
Dim Rw As Long: Rw = 4
With ThisWorkbook.Sheets("Calculation")
Debug.Print "=IF(" & Col & Rw & "=""-"",""-"",Cars!" & Col & Rw & "*" & Col & Rw & "*Data!$C$8)"
.Cells(Rw + 1, Col).Formula = "=IF(" & Col & Rw & "=""-"",""-"",Cars!" & Col & Rw & "*" & Col & Rw & "*Data!$C$8)"
End With
End Sub
So what you might forget easily is to use the , as parameter delimiter in a VBA programmed formula. When you put this on your sheet Excel will automatically replace that with the appropriate delimiter for your region.
Another thing to keep in mind; whenever you about to use a string value in such an function, don't forget to wrap it in double quotes!
Don't forget to remove the Debug.print .... line. It was merely there to show the output :)
I have a table in which I count the records through Worksheet.Function.Countif.
It is nice because it counts the rows using .Rows.Count and so I am alwasy ensured if my table changes the size.
It looks like that (subset of the code):
endrow = .Cells(.Rows.Count, 20).End(xlUp).Row
ws1.Cells(6, 34).Formula = "=COUNTIF(" & .Range("U6:U" & endrow).Address & ",U6)"
I wish to write the the worksheet.function formula in the same way as above but for 'Countifs'. In excel, I would type it like that:
=COUNTIFS($U$6:$U$144;U6;$T$6:$T$144$;"<>"&T6)
How to write it in vba, using 'endrow' as in the first demonstarted code, i.e. without '144' as the last row but with '& endrow' ?
I was trying multiple times, but I cannot get it to work :/
I will appreciate any help.
Try this:
ws1.Cells(6, 34).Formula = "=COUNTIFS($U$6:$U$" & endrow & ",U6,$T$6:$T$" & endrow & "," & """" & "<>" & """" & "&T6" & ")"
This formula gets the last row of column A:
=IFERROR(LOOKUP(2,1/(NOT(ISBLANK(A:A))),ROW(A:A)),0)
I've been struggling to get a formula typed into a cell on a sheet. it's my activesheet (definitely).
Source is a file with full path. the sheet name is ... and lta_col_letter is the column letter I'm typing the formula into.
ActiveSheet.Range(lta_col_letter & 2).Formula = "=IFERROR(INDEX('[" & Source & "]...'!$G:$G,MATCH(" & versionref_col_letter & "2,'[" & Source & "]...'!$B:$B,0))," & Chr(34) & Chr(34) & ")"
I'm not sure why I'm getting this error. Help please!
EDIT:
Works when I added the missing [ brackets, but when it goes into the cell it adds the file name again after the sheet name and before the cell reference.It looks fine in a msgbox.
Looks like you are missing some opening square brackets around source.
ActiveSheet.Range(lta_col_letter & 2).Formula = "=IFERROR(INDEX('[" & source & "]...'!$G:$G,MATCH(" & versionref_col_letter & "2,'[" & source & "]...'!$B:$B,0)), text(,))"
To examine these types of errors, put a ' before the opening = and run the procedure to put the formula into the cell as a string. Go to the worksheet and perform a visual examination and try to remove the '. Make corrections until you have a working formula then transfer the corrections to the VBA formula string.
Since it seems that you have used an open workbook to retrieve the workbook name into source, you might consider using the Range.Address Property with External:=True to retrieve a fully punctuated external address.
dim sourceG as string, sourceB as string
sourceG = workbooks(source).worksheets("...").range("G:G").address(external:=true)
sourceB = workbooks(source).worksheets("...").range("B:B").address(external:=true)
ActiveSheet.Range(lta_col_letter & 2).Formula = _
"=IFERROR(INDEX(" & sourceG & ", MATCH(" & versionref_col_letter & "2, " & sourceB
& ",0)), text(,))"
I am quite new to VBA so I am sorry if my question might seems very trivial.
I would love to write a function in VBA which helps to estimate weighted average rate (for loan portfolio, for instance). I wrote the following VBA code:
Function WAIRS(Amount As Range, InterestRate As Range, MatchRange As Range, Match1)
WAIRS = Evaluate("=SUMPRODUCT(--(""" & MatchRange & """ = """ & Match1 & """),""" & Amount & """, """ & InterestRate & """)") /Application.WorksheetFunction.SumIfs(Amount, MatchRange, Match1)
End Function
The problem is that when I run this function in Excel by adding respective function criterias I get an "#VALUE#". I have tried a lot but cannot find out what is wrong. I Would highly appreciate if you can help me.
Thank you in advance.
Best,
Jeyhun
The string you build for Evaluate should (in this case) not include literal double quotes. Instead of quoting the result of a range value
"""" & MatchRange & """"
...you should retrieve the address notation of that range, and use that without wrapping it in quotes:
MatchRange.Address()
If you apply that consistently, it would make the Evaluate part of the formula look like this:
"=SUMPRODUCT(--(" & MatchRange.Address() & " = " & Match1.Address() & "), " & _
Amount.Address() & ", " & InterestRate.Address() & ")"
When range is another sheet:
The above will not work if your ranges are on another sheet. In that case, I would suggest to create this function:
Public Function fullAddr(range As Range)
fullAddr = "'" & range.Parent.Name & "'!" & _
range.Address(External:=False)
End Function
And then in your formula:
"=SUMPRODUCT(--(" & fullAddr(MatchRange) & " = " & fullAddr(Match1) & "), " & _
fullAddr(Amount) & ", " & fullAddr(InterestRate) & ")"
I'm trying to get this segment of code to execute. This is a simplified version of the code. I've included the relevant code. I'm trying to concatenate strings and named ranges into a SumIfs formula, but I get error 1004 "Application-defined or Object-defined error." I have a working line of code above this problem section that is similar with the exception of doing a sum function, instead of sumif. Any idea how to get this code to execute? Thank you.
Dim wb As Workbook
Dim ara As Worksheet
Dim inv As Worksheet
Dim ARBlock As Range
Dim Invoices As Range
Dim AgedDays As Range
Set wb = ThisWorkbook
Set ara = wb.Sheets("AR Aging")
Set inv = wb.Sheets("Invoices")
Set ARBlock = ara.Range("a6")
Set Invoices = inv.Range("a6", inv.Range("a6").End(xlDown))
Set AgedDays = Invoices.Offset(0, 6)
'Populate A/R age buckets
For i = 6 To ARBlock.Rows.Count + 6
With ARBlock(i - 5, 1).Offset(0, 3)
.Value = "=SumIfs(" & Invoices.Offset(0, 4).Address & "," & _
Invoices.Address & "," & ARBlock(i - 5, 1).Value & "," & _
Invoices.Offset(0, 6).Address & ","" <= "" & &O30)"
End With
Next i
End Sub
The line beginning with ".value" is where I'm getting the error message. P.S.: I need the cell to contain the concatenated formula, as opposed to the output value.
UPDATE 1:
As some suggested I updated the .value line to:
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
I'm still getting the same error. Some auditing I've done:
Removing the "=" before "Sumifs" allows the code to run fine; pasting in the formula into the target cell as text. In this form, my output for i=1 goes to ARBlock.cells(1,1), as it should.
I also used Debug.Print to view all of the components of the formula:
Debug.Print ARBlock.Cells(i - 5, 1).Address
'output $A$6
Debug.Print ARBlock.Cells(i - 5, 1).Value
' output International Business Machines
Debug.Print Invoices.Offset(0, 4).Address
'output $E$6:$E$255
Debug.Print Invoices.Address
'output $A$6:$A$255
I suspected the issue might be that the range dimensions might have been off, but this is not the case. My next suspicion is that the output International Business Machines needs to be in " " for the formula to read it correctly. I hardcoded in
""International Business Machines""
to see if this would fix the formula, but I keep getting the same error once I add the "=" back in. The formula syntax is correct, the dimensions are the same between the sum range and criteria range. Anyone else have any ideas?
.Offset(0, 3).Formula = "=SumIfs(Invoices.Offset(0, 4).Address,Invoices.Address,ARBlock.cells(i - 5, 1).Value)"
Change to:
.Offset(0, 3).Formula = "=SumIfs(" & Invoices.Offset(0, 4).Address & ", " & Invoices.Address & ", " & chr(34) & ARBlock.Cells(i - 5, 1).Value & chr(34) & ")"
EDIT: Added quotes chr(34) around your string!
Your ARBlock(i - 5, 1).Value most likely is an empty cell, which messes the SUMIFS formula as it builds it with to consecutive commas