Sub Weld_Scrap()
'Copying Column with date selected in it
Columns("I").Copy
Columns("X").Select
ActiveSheet.Paste
'Deleting unnecessary cells
Rows("1:7").Delete
Columns("B:Q").Delete
'Selecting range for dictionary
Dim rng As Range, dict As Object
'Offsets range selected from column A
Set rng = Range(Range("A2"), Cells(Rows.Count, 1).End(xlUp)).Resize(, 2)
'Puts associated dollar values into column D and sets Subtotals function
Set dict = SubTotals(rng, 1, 2)
DumpDict dict, Range("D1")
End Sub
'k = code
'v = dollars
'Creates dictionary using a range and an object
'Also runs subtotal
Function SubTotals(rng As Range, colKey As Long, colVal As Long) As Object
Dim rv As Object, rw As Range, k, v
Set rv = CreateObject("scripting.dictionary")
For Each rw In rng.Rows
k = rw.Cells(colKey).Value
v = rw.Cells(colVal).Value
If Not IsError(k) And Not IsError(v) Then
If Len(k) > 0 And IsNumeric(v) Then
rv(k) = rv(k) + v
End If
End If
Next rw
Set SubTotals = rv
End Function
'Offsets value of column A so that the values being subtotaled are the values associated with their scrap codes
Sub DumpDict(dict As Object, rng As Range)
Dim i As Long, k
i = 0
For Each k In dict.keys
With rng.Cells(1)
.Offset(i, 0).Value = k
.Offset(i, 1).Value = dict(k)
End With
i = i + 1
Next
'Now the codes are matched with their subtotals
'Deleting all rows that don't contain a scrap code
Dim dontDelete
dontDelete = Array("7101", "7102", "7103", "7104", "7105", "7106", "7107", "7108", "7109", "7110", "7111", "7112", "7113", "7114", "7115", "7116")
Dim o As Long, p As Long
Dim isThere As Boolean
'Loop for deleting, shifts cells up
For o = Range("D" & Rows.Count).End(xlUp).Row To 1 Step -1
For p = LBound(dontDelete) To UBound(dontDelete)
If StrComp(Range("D" & o), dontDelete(p), vbTextCompare) = 0 Then
isThere = True
End If
Next p
If Not isThere Then
Range("D" & o).EntireRow.Delete Shift:=xlUp
End If
isThere = False
Next o
'Sorts codes from least to greatest
Dim lr As Long
Application.ScreenUpdating = False
lr = Cells(Rows.Count, 1).End(xlUp).Row
Range("E1:D" & lr).Sort key1:=Range("D1"), order1:=1
Application.ScreenUpdating = True
'Inserts blank cells for scrap codes that have no values
Dim m As Long, z, r As Range
For m = Range("d" & Rows.Count).End(xlUp).Row To 2 Step -1
z = Mid$(Cells(m, "d"), 2) - Mid$(Cells(m - 1, "d"), 2)
If z > 1 Then
Rows(m).Resize(z - 1).Insert
Cells(m - 1, "d").AutoFill Cells(m - 1, "d").Resize(z), 2
End If
Next
'Giving headers to data
Rows(1).Insert Shift:=xlDown
Range("$D$1").Value = "Scrap Code"
Range("$E$1").Value = "Scrap Dollars"
'Puts date in A1 for loop to recognize
With ActiveSheet
LastVal = Range("H65536").End(xlUp)
End With
Range("A1") = LastVal
'Copies range of cells
End Sub
Bookmarks