calculating loop didn't work vba - excel

I am trying to calculate from range M13:M22 using some conditional values and looping, but some of my code just works only in cell M13 and doesn't loop to cell M22. How do I solve this problem?
Here is my code:
Private Sub CommandButton1_Click()
Dim pelanggan As Range, alamat As Range, diskon As Range, jdiskon As Range, tanggal As Range, jtempo As Range
Dim rout(1 To 10) As Variant, i As Long
Dim path As String
path = "\\Faizal\Data D Faizal\Daftar Harga\Price List"
Filename = Dir(path & "database.xlsx")
Set pelanggan = Range("E7")
Set alamat = Range("E8")
Set diskon = Range("L25")
Set tanggal = Range("L7")
Set jdiskon = Range("P13")
Set jtempo = Range("K30")
getalamat = Application.WorksheetFunction.VLookup(pelanggan & Range("J7"), Workbooks("database.xlsx").Worksheets("DB").Range("A6:N1350"), 14, False)
getdiskon = Application.WorksheetFunction.VLookup(pelanggan & Range("J7"), Workbooks("database.xlsx").Worksheets("DB").Range("A6:N1350"), 6, False)
getjdiskon = Application.WorksheetFunction.VLookup(pelanggan & Range("J7"), Workbooks("database.xlsx").Worksheets("DB").Range("A6:N1350"), 11, False)
getjtempo = Application.WorksheetFunction.VLookup(pelanggan & Range("J7"), Workbooks("database.xlsx").Worksheets("DB").Range("A6:N1350"), 13, False)
alamat.Value = getalamat
diskon.Value = getdiskon / 100
jdiskon.Value = getjdiskon
tanggal.Value = DateValue(Now)
jtempo.Value = getjtempo
'here is the calculation that won't go loop
For i = 13 To 22
getharga = Application.WorksheetFunction.VLookup(Range("D" & i) & Range("E" & i), Workbooks("database.xlsx").Worksheets("Gold").Range("E4:H80"), 4, False)
If jdiskon = "Nett" Then
Range("M" & i).Value = getharga - (getharga * diskon)
Range("L25").ClearContents
ElseIf jdiskon = "Pot" Then
Range("M" & i).Value = getharga
Range("L25").Value = diskon
ElseIf jdiskon = "Diskon Kitir" Then
Range("M" & i).Value = getharga
Range("L25").ClearContents
End If
Next
End Sub

Your question: "... my code just works only in cell M13 and doesn't loop to cell M22. How do I solve this problem?"
Your loop is ok, so that is not the problem you have to solve.
You have to debug to find the causes of your loop not performing the actions you mean to.
I am posting below modified code, with two features: 1) it fully qualifies Ranges, so you avoid unexpected errors, you may want to check this; 2) it uses MsgBoxes, one way of debugging.
This will likely pinpoint the "error".
Private Sub CommandButton1_Click()
Dim pelanggan As Range, alamat As Range, diskon As Range, jdiskon As Range, tanggal As Range, jtempo As Range
Dim rout(1 To 10) As Variant, i As Long
Dim path As String
path = "\\Faizal\Data D Faizal\Daftar Harga\Price List"
Filename = Dir(path & "database.xlsx")
Dim wb as Workbook, ws1 as Worksheet, ws2 as Worksheet, rng1 as Range
Set wb = Workbooks("database.xlsx")
Set ws1 = wb.Worksheets("DB")
Set ws2 = wb.Worksheets("Gold")
Set rng1 = ws.Range("A6:N1350")
Set pelanggan = ws1.Range("E7")
Set alamat = ws1.Range("E8")
Set diskon = ws1.Range("L25")
Set tanggal = ws1.Range("L7")
Set jdiskon = ws1.Range("P13")
Set jtempo = ws1.Range("K30")
Dim rng2 as Range
Set rng2 = ws1.Range(pelanggan.Value & ws1.Range("J7").Value)
getalamat = Application.WorksheetFunction.VLookup(rng2, rng1, 14, False)
getdiskon = Application.WorksheetFunction.VLookup(rng2, rng1, 6, False)
getjdiskon = Application.WorksheetFunction.VLookup(rng2, rng1, 11, False)
getjtempo = Application.WorksheetFunction.VLookup(rng2, rng1, 13, False)
alamat.Value = getalamat
diskon.Value = getdiskon / 100
jdiskon.Value = getjdiskon
tanggal.Value = DateValue(Now)
jtempo.Value = getjtempo
'here is the calculation that won't go loop
For i = 13 To 22
Dim rng3 as Range
Set rng3 = ws1.Range(ws1.Range("D" & i).Value & ws1.Range("E" & i).Value)
getharga = Application.WorksheetFunction.VLookup(rng3, ws2.Range("E4:H80"), 4, False)
MsgBox "getharga = " & getharga & " for i = " & i
If jdiskon = "Nett" Then
ws1.Range("M" & i).Value = getharga - (getharga * diskon)
ws1.Range("L25").ClearContents
ElseIf jdiskon = "Pot" Then
ws1.Range("M" & i).Value = getharga
ws1.Range("L25").Value = diskon
ElseIf jdiskon = "Diskon Kitir" Then
ws1.Range("M" & i).Value = getharga
ws1.Range("L25").ClearContents
Else
MsgBox "jdiskon = " & jdiskon & " for i = " & i
End If
Next
End Sub
(PS: I do not currently have a system with Excel, so this code may need little adjustments).

sorry for late review, i change my "dim diskon as Range" into "dim diskon as Variant" n then my code works perfectly.
Thanks for your effort to help me.

Related

Cannot run the coding for VBA GoalSeeker

Sub Goal Seek()
Dim i As Integer
Dim ResultQty As Integer
Dim ChangingCell As Integer
Dim TargetSales As Integer
For i = 4 To 18
TargetSales = Cells(i,7).value
Cells(i, 6).Formula = "(C" & i & "*" & "E" & i & ")"
Set ResultQty = Cells(i,6).value
Set ChangingCell = Cells(i,3).value
ResultCell.GoalSeek TargetSales, ChangingCell
Next i
End Sub
I want to get the Qty from goal seeker by setting the targeted sales. But the code shows error. Can anyone help with it?
'=' missing in formula cell, target cell should not be integer as values are higher than range allowed
Sub GoalSeek()
Dim i As Integer
Dim ResultCell As Range
Dim TargetSales As Variant
For i = 4 To 18
Set ResultCell = Cells(i, 3)
TargetSales = Cells(i, 7).Value
Set ResultCell = Cells(i, 6)
ResultCell.Formula = "=(C" & i & "*" & "E" & i & ")"
ResultCell.GoalSeek TargetSales, Range("C" & i)
Next i
End Sub

Why is multiple Application.VLookup into array dreadfully slow?

I have an external workbook from which I need to get data into my main workbook.
In the past i did this using A LOT of vlookups - and as a result the calculation was extremely slow. In order to speed things up, I have tried to convert the data from the external workbook into an array(arr2), and then doing the lookups into this. The result is that it's even more slow now..
The lookup value is composed of the values from two cells. I roughly have 1000 rows which, the way i do it, needs to be looped through in 44 columns. While it is actually working on a limited amount of rows, after one hour it is still processing when listing all 1000 rows.
What can be done to speed things up?
Dim arr1() As Variant, arr2() As Variant, arr3() As Variant
Dim sup1 As Long, sup2 As Long, sup3 As Long, sup4 As Long, sup5 As Long, sup6 As Long, sup7 As Long,
sup8 As Long, sup9 As Long, sup10 As Long, sup11 As Long, sup12 As Long, sup13 As Long, sup14 As
Long, sup15 As Long
Dim i As Long, WS1 As Worksheet
Dim Book1 As Workbook, book2 As Workbook
Dim book2Name As String
book2Name = "SupportTables.xlsx"
Dim book2NamePath As String
book2NamePath = ThisWorkbook.Path & "\" & book2Name
Dim lastrow As Long
lastrow = Sheets("sheet1").Range("T" & Rows.Count).End(xlUp).Row
Set Book1 = ThisWorkbook
If IsOpen(book2Name) = False Then Workbooks.Open (book2NamePath)
Set book2 = Workbooks(book2Name)
Set WS1 = book2.Worksheets("pricediscinfo")
sup1 = Range("AN12")
sup2 = Range("AQ12")
...
sup15 = Range("CD12")
arr1 = Range("T15:T" & lastrow)
ReDim arr3(1 To UBound(arr1), 1 To 44)
arr2 = WS1.Range("a1").CurrentRegion.Value
For i = 1 To UBound(arr1)
arr3(i, 1) = Application.VLookup(arr1(i, 1) & sup1, arr2, 12, False)
arr3(i, 2) = Application.VLookup(arr1(i, 1) & sup1, arr2, 9, False)
...
arr3(i, 43) = Application.VLookup(arr1(i, 1) & sup15, arr2, 12, False)
arr3(i, 44) = Application.VLookup(arr1(i, 1) & sup15, arr2, 9, False)
Next i
Range("AN15:CE" & lastrow).Value = arr3
Any input appriciated!
Dictionaries are just a collection of key, value pairs like an 1 dimension array but with a string allowed as the key rather than just numbers. In this case because you want to look up 2 columns, the value that a key refers to I chose to be a 2 element array. For more complex cases you might just store the row number as the dictionary value and use it to get the value of any column on the lookup sheet (or array). See Dictionary Object
Update : (ws2.Cells(1, "I") corrected to (ws2.Cells(i, "I")
Option Explicit
Sub FasterLookUp()
Const WB2_NAME = "SupportTables.xlsx"
Const WS2_NAME = "pricediscinfo"
Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Dim iLastrow As Long, i As Long
Dim arr1, arr2, arr3, sPath As String, s As String
Dim isOpen As Boolean, t0 As Single
Dim dict As Object, k
Set dict = CreateObject("Scripting.Dictionary")
Set wb1 = ThisWorkbook
Set ws1 = wb1.Sheets("Sheet1")
sPath = wb1.Path & "\"
' configuration
Dim sup(15) As String, supCol
supCol = Array("AN", "AQ", "AR", "AS", "AT", _
"AU", "AV", "AW", "AX", "AY", _
"AZ", "BA", "BB", "BC", "CD")
For i = 1 To 15
sup(i) = ws1.Cells(12, supCol(i - 1))
s = s & "sup(" & i & ") = " & sup(i) & vbCr
Next
MsgBox s ' for checking code
' open workbook if not already open
isOpen = False
For Each wb2 In Application.Workbooks
If wb2.Name = WB2_NAME Then
isOpen = True
Exit For
End If
Next
If isOpen = False Then
Set wb2 = Workbooks.Open(sPath & "\" & WB2_NAME, True, True) ' update links, read only
End If
Set ws2 = wb2.Sheets(WS2_NAME)
iLastrow = ws2.Cells(Rows.Count, "A").End(xlUp).Row
' build dictionary as lookup table
t0 = Timer
For i = 1 To iLastrow
k = Trim(ws2.Cells(i, "A")) ' key
If Len(k) > 0 Then
If dict.exists(k) Then
MsgBox "Duplicate key " & k, vbCritical, "Row " & i
Exit Sub
Else
' col I and col L
dict.Add k, Array(ws2.Cells(i, "I"), ws2.Cells(i, "L")) ' lookups
End If
End If
Next
MsgBox dict.Count & " Items scanned into dictionary from " & ws2.Name, _
vbInformation, "Took " & Int(Timer - t0) & " seconds"
' update this workbook
t0 = Timer
iLastrow = ws1.Cells(Rows.Count, "T").End(xlUp).Row
arr1 = ws1.Range("T15:T" & iLastrow)
ReDim arr3(UBound(arr1), 1 To 44)
For i = 1 To UBound(arr1)
s = arr1(i, 1)
k = s & sup(1)
If dict.exists(k) Then
arr3(i, 1) = dict(k)(1) ' col L
arr3(i, 2) = dict(k)(0) ' col I
Else
'Debug.Print "No match '" & k & "'"
End If
''
k = s & sup(15)
If dict.exists(k) Then
arr3(i, 1) = dict(k)(1) ' col L
arr3(i, 2) = dict(k)(0) ' col I
Else
'Debug.Print "No match '" & k & "'"
End If
Next i
If isOpen = False Then wb2.Close False ' close if opened
ws1.Range("AN15:CE" & iLastrow).Value = arr3
MsgBox "Udate done", vbInformation, "Took " & Int(Timer - t0) & " seconds"
End Sub

Run-time error '438': Object does't support this property or method

Following macro nearly works flawless up to one specific line.
Sub Top15()
Dim Top15 As Worksheet
Dim lastROW As Long
Dim last15ROW As Long
Dim rangeC As Range
Dim rangeH As Range
Dim rangeI As Range
Dim rangeJ As Range
Dim rangeK As Range
Dim rangeL As Range
Dim rangeM As Range
Dim rangeN As Range
Dim pasteRange As Range
Set Top15 = ThisWorkbook.Sheets("03")
lastROW = Top15.Range("C" & Top15.Rows.Count).End(xlUp).Row + 1
last15ROW = Top15.Range("C" & Top15.Rows.Count).End(xlUp).Row + 16
Set rangeC = Top15.Range("C" & lastROW & ":C" & last15ROW)
Set rangeH = Top15.Range("H" & lastROW & ":H" & last15ROW)
Set rangeI = Top15.Range("I" & lastROW & ":I" & last15ROW)
Set rangeJ = Top15.Range("J" & lastROW & ":J" & last15ROW)
Set rangeK = Top15.Range("K" & lastROW & ":K" & last15ROW)
Set rangeL = Top15.Range("L" & lastROW & ":L" & last15ROW)
Set rangeM = Top15.Range("M" & lastROW & ":M" & last15ROW)
Set rangeN = Top15.Range("N" & lastROW & ":N" & last15ROW)
With Top15
rangeC.Formula = "=TEXT(WEEKNUM(TODAY()),""0#"")" 'CW
rangeH.Formula = "=IF(ISBLANK(INDIRECT(""D""&ROW())),"""",INDIRECT(""D""&ROW())&""/""&TEXT(INDIRECT(""C""&ROW()),""0#""))" 'REF
rangeI.Formula = "=IFERROR(IF(RIGHT(VLOOKUP(INDIRECT(""D""&ROW())&""/""&TEXT(INDIRECT(""C""&ROW())-1,""0#""),H:H,1,FALSE),2)+1=INDIRECT(""C""&ROW()),INDIRECT(""C""&ROW()),1),1)" 'open weeks
rangeJ.Forumla = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,3,FALSE),"""")" 'Issue description
rangeK.Forumla = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,4,FALSE),"""")" 'action
rangeL.Formula = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,5,FALSE),"""")" 'reason
rangeM.Formula = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,6,FALSE),"""")" 'missing component
rangeN.Formula = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,7,FALSE),"""")" 'expected D CW
Set pasteRange = .Range(rangeC.Address & ":" & rangeN.Address)
pasteRange.Copy
pasteRange.PasteSpecial xlPasteValues
End With
End Sub
The first three functions work but I'm getting the run-time error at the third one:
With Top15
rangeC.Formula = "=TEXT(WEEKNUM(TODAY()),""0#"")" 'CW
rangeH.Formula = "=IF(ISBLANK(INDIRECT(""D""&ROW())),"""",INDIRECT(""D""&ROW())&""/""&TEXT(INDIRECT(""C""&ROW()),""0#""))" 'REF
rangeI.Formula = "=IFERROR(IF(RIGHT(VLOOKUP(INDIRECT(""D""&ROW())&""/""&TEXT(INDIRECT(""C""&ROW())-1,""0#""),H:H,1,FALSE),2)+1=INDIRECT(""C""&ROW()),INDIRECT(""C""&ROW()),1),1)" 'open weeks
rangeJ.Forumla = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,3,FALSE),"""")" 'Issue description
rangeK.Forumla = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,4,FALSE),"""")" 'action
rangeL.Formula = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,5,FALSE),"""")" 'reason
rangeM.Formula = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,6,FALSE),"""")" 'missing component
rangeN.Formula = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,7,FALSE),"""")" 'expected D CW
This is the formula that is giving me the run-time error->
rangeJ.Forumla = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,3,FALSE),"""")" 'Issue description
Anyone knows why VBA has a problem with that formula?
you have mispelled the range.Formula
Your line:
rangeJ.Forumla =
Should be:
rangeJ.Formula =
Happens twice:
rangeJ.Forumla = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,3,FALSE),"""")" 'Issue description
rangeK.Forumla = "=IFERROR(VLOOKUP((INDIRECT(""D""&ROW())&""/""&TEXT((INDIRECT(""C""&ROW())-1),""0#"")),$H:$N,4,FALSE),"""")" 'action
Please mark answer as correct if you agree.
Hope it helps!

Move Two characters from beginning to end of string VBA

I need to create a VBA script in excel that chanages an order number from having "CD" at the front to "CD" at the end so from "CD00001" to "00001CD"
Any help would be awesome. all of the order numbers are in Column B and start at row 5. please help.
What i have so far:
Private Sub OrderNumber_Click()
Dim Val As String
Dim EndC As Integer
EndC = Worksheets("Raw Data Upload").Range("A1048576").End(xlUp).Row
For i = 5 To EndC
Val = Right("B" & i, Len("B" & i) - 2) & Left("B" & i, 2)
Range("B" & i).Value = Val
Next
End Sub
This replaces the order numbers with B5, B6 and so on but if i put this function into Excel itself it works fine.
Like this? DO you want it in column B?
Option Explicit
Private Sub OrderNumber_Click()
Dim i As Long
Dim val As String
Dim EndC As Long
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets("Raw Data Upload")
EndC = ws.Range("A1048576").End(xlUp).Row
For i = 5 To EndC
val = ws.Cells(i, "A")
Range("B" & i).Value = Mid$(val, 3, Len(val) - 2) & Left$(val, 2)
Next i
End Sub
dim beginStr, endStr, originalStr, outputStr as string
dim rng as range
'put the below into a loop, assigning a rng to the desired cell each time
originalStr = rng.value ' Change to chosen range
beginStr = left(originalStr,2)
endStr = right(originalStr, len(originalStr) - 2)
outputStr = endStr + beginStr
Range("B" & i).Value = outputStr
I haven't got a copy of Excel to test this on but it should work.
Simply use:
Right(Range("B" & i), Len(Range("B" & i)) - 2) & Left(Range("B" & i), 2)
An alternative is to set up the cell as a Range():
Sub t()
Dim cel As Range
Dim endC As Long
endC = Worksheets("Raw Data Upload").Range("A1048576").End(xlUp).Row
For i = 5 To endC
Set cel = Range("B" & i)
myVal = Right(cel, Len(cel) - 2) & Left(cel, 2)
Range("B" & i).Value = myVal
Next
End Sub
Currently, when you do Right("B" & i, Len("B" & i) - 2) & Left("B" & i, 2), for row 5, this becomes Right("B5", Len("B5") - 2) & Left("B5", 2) then this evaluates to simply:
Right("B5",0) & Left("B5",2), which is
[nothing] & B5, finally becoming
B5
Note the lack of using B5as a range. Instead it's being treated as a string.
(Also, I'm assuming this is to be run on the ActiveSheet. If not, please add the worksheet before the range, i.e. Worksheets("Raw Data Upload").Range("B" & i)...)
Try this
Private Sub OrderNumber_Click()
Dim cell As Range
With Worksheets("Raw Data Upload")
For Each cell in .Range("B5", .Cells(.Rows.Count, 2).End(xlUp))
cell.Value = Right(cell.Value, Len(cell.Value) - 2) & Left(cell.Value, 2)
Next
End With
End Sub

Excel VBA SUMIF Super slow code

I have SUMIF running really really slow. My data has 14,800 Rows and 39 Columns.
I do the following:
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
ActiveSheet.DisplayPageBreaks = False
EDITED TO ADD more potentially relevant code that may be interacting with the SUMIF command
It may be relevant to the speed issue so I'll mention it. I get the user to open a file from wherever they may have stored the report. The file then stays open. Maybe that is a problem. I don't know if it should be some other way.. like I close it but keep the address in mind or something??
FilterType = "Text Files (*.txt),*.txt," & "Comma Separated Files (*.csv),*.csv," & "ASCII Files (*.asc),*.asc," & "All Files (*.*),*.*"
FilterIndex = 4
Title = "File to be Selected"
File_path = Application.GetOpenFilename(FileFilter:=FilterType, FilterIndex:=FilterIndex, Title:=Title)
If File_path = "" Then
MsgBox "No file was selected."
Exit Sub
End If
Set wbSource = Workbooks.Open(File_path)
Original_Name = ActiveWorkbook.Name
If ActiveSheet.AutoFilterMode Then
ActiveSheet.AutoFilterMode = False
End If
Set wb1 = ActiveWorkbook
Set ws1 = wb1.Worksheets("Sheet1")
With ws1
FinalColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
FinalRow = .Range("B" & .Rows.Count).End(xlUp).Row
For j = 1 To FinalColumn
If .Cells(1, j).Value = "Effec.Date" Then
Effective_Date_Column = j
ElseIf .Cells(1, j).Value = "FolderId" Then
FolderId_column = j
ElseIf .Cells(1, j).Value = "FolderNotional" Then
FolderNotional_column = j
End If
Next j
'range_Total_Folder_Fixed = .Cells(2, Total_Folder_Column).Address & ":" & .Cells(FinalRow, Total_Folder_Column).Address
range_FolderId_Fixed = .Cells(2, FolderId_column).Address & ":" & .Cells(FinalRow, FolderId_column).Address
range_FolderId_Cell = .Cells(2, FolderId_column).Address(RowAbsolute:=False, ColumnAbsolute:=False)
range_FolderNotional_Fixed = .Cells(2, FolderNotional_column).Address & ":" & .Cells(FinalRow, FolderNotional_column).Address
Everything runs in 8-10 seconds until we come to the lie below. Now the total time jumps to a 150 seconds.
.Range(range_Total_Folder_Fixed).Formula = "=SUMIF(" & range_FolderId_Fixed & "," & range_FolderId_Cell & "," & range_FolderNotional_Fixed & ")"
Am I doing something wrong? Is there a better (more efficient) way to write a general formula?
EDIT: Code generated Raw Formula
Some of the excel worksheet functions in my code:
.Range(range_Isnumber).Formula = "=(RIGHT(" & range_TradeId_cell & ",2)<> ""IB"")*1"
.Range(range_Is_IB).Formula = "=(RIGHT(" & range_TradeId_cell & ",2)= ""IB"")*1"
.Range(range_Exceptions).Formula = "=(SUMIF(" & range_FolderId_Fixed & "," & range_FolderId_Cell & "," & range_Isnumber_fixed & ")= COUNTIF(" & range_FolderId_Fixed & "," & range_FolderId_Cell & "))*1+(SUMIF(" & range_FolderId_Fixed & "," & range_FolderId_Cell & "," & range_Is_IB_fixed & ")= COUNTIF(" & range_FolderId_Fixed & "," & range_FolderId_Cell & "))*1 "
.Range("C13").FormulaR1C1 = "=SUM(IF(FREQUENCY(MATCH([SCL_FL_2013_11_30.xlsx]Rest!R2C2:R2321C2,[SCL_FL_2013_11_30.xlsx]Rest!R2C2:R2321C2,0),MATCH([SCL_FL_2013_11_30.xlsx]Rest!R2C2:R2321C2,[SCL_FL_2013_11_30.xlsx]Rest!R2C2:R2321C2,0))>0,1))"
So Stuff like
Range("I2")=SUMIF($H$2:$H$5,H2,$G$2:$G$5)
Where the data could be like
RowG RowH RowI
Alice 1 4
Alice 3 4
Bob 9 17
Bob 8 17
Dan 2 2
EDIT2 : Implementing Sam's solution, I am getting errors:
Set range_FolderId_Fixed = .Range(.Cells(2, FolderId_column), .Cells(FinalRow, FolderId_column))
Set range_FolderId_Cell = .Range(.Cells(2, FolderId_column),.Cells(FinalRow, FolderId_column))
Set range_FolderNotional_Fixed = .Range(.Cells(2, FolderNotional_column), .Cells(FinalRow, FolderNotional_column))
Set range_Total_Folder_Fixed = .Range(.Cells(2, Total_Folder_Column), .Cells(FinalRow, Total_Folder_Column))
.Range(range_Total_Folder_Fixed).Value = SumIf_func(range_FolderId_Fixed, range_FolderId_Cell, range_FolderNotional_Fixed)
I am getting a type application defined or object defined error in the line below.
.Range(range_Total_Folder_Fixed).Value = SumIf_func(range_FolderId_Fixed, range_FolderId_Cell, range_FolderNotional_Fixed)
I have no idea what to do next.
Ok this is what I came up with
Public Function SumIf_func(rng As Range, _
criteria As Range, _
sumRange As Range) As Variant()
Dim rngArr() As Variant
Dim sumArr() As Variant
Dim criteriaArr() As Variant
Dim returnArr() As Variant
Dim temp As Double
rngArr = rng.Value2
sumArr = sumRange.Value2
criteriaArr = criteria.Value2
If UBound(sumArr) <> UBound(rngArr) Then _
Err.Raise 12345, "SumIf_func", "Sum range and check range should be the same size"
If UBound(sumArr, 2) <> 1 Or UBound(rngArr, 2) <> 1 Then _
Err.Raise 12346, "SumIf_func", "Sum range and check range should be a single column"
ReDim returnArr(1 To UBound(criteriaArr), 1 To 1)
For c = LBound(criteriaArr) To UBound(criteriaArr)
returnArr(c, 1) = Application.WorksheetFunction.SumIf(rng, criteriaArr(c, 1), sumRange)
Next c
SumIf_func = returnArr
End Function
This function takes in three ranges:
The range to check
The range where the criteria are
The range where the values to sum are
The range to check and the sum range should both be the same length and only be 1 column across.
The array that is returned will be the same size as the criteria array..
Here is an example of usage:
Public Sub test_SumIf()
Dim ws As Worksheet
Set ws = Sheet1
Dim rng As Range, sumRng As Range, criteria As Range
Set rng = ws.Range("A1:A100")
Set sumRng = ws.Range("B1:B100")
Set criteria = ws.Range("C1:C10")
ws.Range("D1:D10").Value = SumIf_func(rng, criteria, sumRng)
End Sub

Resources