explain the code: Private Sub M1_Reset_Sheet()
Application.DisplayAlerts = False
'=================================================================================================================================
'Created By Halley Szeto, PI Analyst, Customer Excellence - 12 May 21
'Resets All Sheets
'=================================================================================================================================
'Confirmation
'User Input
iRConf = MsgBox("This will remove submitted SKUs" & vbCrLf & vbCrLf & _
"Proceed?", vbYesNo, "Reset Confirmation")
'If no
If iRConf = vbNo Then
Exit Sub
End If
'Reset Data SKUs
'Activate Sheet
iwsDT1.Activate
'Delete All
On Error Resume Next
Range("A1:A" & Range("B" & Rows.Count).End(xlUp).Row).EntireRow.Delete
'Reset Headers
Range("A1") = "SKU"
Range("B1") = "Status"
Range("C1") = "Plant"
'Set Dropdown for Status
'Block/Unblock
With iwsDT1.Range("B2:B1000").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="='" & iwsCS.Name & "'!T3:T4"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
'Reset Tracker Sheet
'Activate Sheet
iwsDISP1.Activate
'Set Font
With iwsDISP1.Range("E7:W" & Range("A" & Rows.Count).End(xlUp).Row).Font
.ThemeColor = xlThemeColorLight1
.TintAndShade = 0
End With
'Find Unblock from previous run and set to open
For Each iColCK In Range("E6:W6")
'Select and Get Column Unblock
iColCK.Select
iColFmt = Left(Right(Cells(1, iColCK.Column).Address, _
Len(Cells(1, iColCK.Column).Address) - 1), _
Application.Search("$", Right(Cells(1, iColCK.Column).Address, _
Len(Cells(1, iColCK.Column).Address) - 1)) - 1)
'Loop and Set Unblock to Open
'Set Unblock Row
iDelCt = Application.IfError(Application.Match("Unblock", iwsDISP1.Range(iColFmt & ":" & iColFmt), 0), 0)
'Do Until all reset
Do Until iDelCt = 0
'Set Text
Range(iColFmt & iDelCt).Select
Range(iColFmt & iDelCt) = "Open"
'Set Green Format
With Range(iColFmt & iDelCt).Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 5296274
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'Reset Unblock Row
iDelCt = Application.IfError(Application.Match("Unblock", iwsDISP1.Range(iColFmt & ":" & iColFmt), 0), 0)
Loop
'Loop and Set Block to Closed
'Set Unblock Row
iDelCt = Application.IfError(Application.Match("Block", iwsDISP1.Range(iColFmt & ":" & iColFmt), 0), 0)
'Do Until all reset
Do Until iDelCt = 0
'Set Text
Range(iColFmt & iDelCt).Select
Range(iColFmt & iDelCt) = "Closed"
'Reset Unblock Row
iDelCt = Application.IfError(Application.Match("Block", iwsDISP1.Range(iColFmt & ":" & iColFmt), 0), 0)
Loop
Next iColCK
Assistant
'Reset Error Report
'Activate Sheet
iwsDISP2.Activate
'Remove All Data
On Error Resume Next
Range("A1:A" & Range("A" & Rows.Count).End(xlUp).Row).EntireRow.Delete
'Reset Headers
Range("A1") = "SKU"
Range("B1") = "Status"
Range("C1") = "Plant"
Range("D1") = "Error Reason"
End Sub
Private Sub M2_Load_Submission_Data()
Application.DisplayAlerts = False
'=================================================================================================================================
'Created By Halley Szeto, PI Analyst, Customer Excellence - 11 Jun 21
'Loads Data
'=================================================================================================================================
Dim iwbSub As Workbook
'Select File to Load
'Set Pathway to Open to
'ChDir ActiveWorkbook.Path,
'Run Dialog with Cancellation Error Handling
cancel = Application.GetOpenFilename _
(Title:="Select Central OU Submission Form to Load")
If cancel = False Then
MsgBox ("Import Session Ended")
Exit Sub
End If
With Workbooks.Open(cancel)
End With
'Set variable Name
Set iwbSub = ActiveWorkbook
Dim iwsImp As Worksheet
'Loop Through All Worksheets
'Activate Workbook
iwbSub.Activate
'Loop and Import Data
For Each iwsImp In Worksheets
'Activate Workbook
iwbSub.Activate
'Unhide workbook if necessary
On Error Resume Next
iwsImp.Visible = True
'Activate Sheet
iwsImp.Activate
'Check Sheet Name - Save if is registered site
'Get Initial Sheet Name
iLoc = Left(iwsImp.Name, 4)
'Skip if Sheet Name is List
If iLoc = "List" Then
GoTo iFunctSkip
End If
'Execute Test
'Activate Sheet
iwsImp.Activate
'Check Database
iLocTest = Application.IfError(Application.Match(iLoc, iwsCS.Range("O:O"), 0), 0) + _
Application.IfError(Application.Match(iLoc, iwsCS.Range("N:N"), 0), 0)
'Actions Test
'If Valid - Import Data
If iLocTest > 0 Then
'Test If Data Exists to Import
If Range("A" & Rows.Count).End(xlUp).Row > 1 Then
'Copy Data
iwsImp.Activate
Range("A2:B" & Range("A" & Rows.Count).End(xlUp).Row).Copy
'Paste Data
iwsDT1.Activate
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Fill Site Number
Range("C" & Range("C" & Rows.Count).End(xlUp).Row + 1 & _
":C" & Range("A" & Rows.Count).End(xlUp).Row) = iLoc
Else
GoTo iFunctSkip
End If
'If Not Valid Set Warning
Else
'Generate Error message
MsgBox ("WARNING! Invalid sheet name detected!" & vbCrLf & vbCrLf & _
"Please validate:" & vbCrLf & vbCrLf & _
iwsImp.Name)
'Error handle
GoTo iFunctSkip
End If
iFunctSkip:
Next iwsImp
'Close Workbook with no Saving
iwbSub.Close savechanges:=False
'Finalize Report
'Set Final View on Data
iwsDT1.Activate
Range("A1").Select
'Set Final View
iwsCS.Activate
Range("A1").Activate
'Completion message
MsgBox ("Submission Data Loaded!")
End Sub
Private Sub M3_Compile_Report()
Application.DisplayAlerts = False
'=================================================================================================================================
'Created By Halley Szeto, PI Analyst, Customer Excellence - 13 May 21
'Compiles Data
'=================================================================================================================================
End Sub
Private Sub M4_Generate_Submission_Form()
Application.DisplayAlerts = False
'=================================================================================================================================
'Created By Halley Szeto, PI Analyst, Customer Excellence - 11 Jun 21
'Generates Distro Form
'=================================================================================================================================
Dim iwbSub As Workbook
Dim iwsSub As Worksheet
'Generage New sheet
'Add New Workbook
Workbooks.Add
Set iwbSub = ActiveWorkbook
Set iwsSub = iwbSub.ActiveSheet
'Generate List Sheet
'Activate Workbook
iwsSub.Activate
'Change Sheet Name
iwsSub.Name = "List"
'Set List
Range("A1") = "Block"
Range("A2") = "Unblock"
'Generate New List
'Copy Data
iwsCFT1.Activate
Range("A1:B" & Range("A" & Rows.Count).End(xlUp).Row).Copy
'Paste Data
iwsSub.Activate
Range("C1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Convert To Numbers
iwsSub.Activate
Columns("C:C").TextToColumns Destination:=Range("C1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
Dim iwsTSN As Worksheet
'Loop and Generate Sheets
'Activate Sheet
iwsCS.Activate
'Loop Through OU List and Grab all West
For Each iOU In Range("Q3:Q" & Range("Q" & Rows.Count).End(xlUp).Row)
'Activate Sheet
iwsCS.Activate
'Select and get row
iOU.Select
iOUR = iOU.Row
'Save Data
iNum = Range("O" & iOUR) 'MU
iOUT = Range("Q" & iOUR) 'OU
iLoc = Range("S" & iOUR) 'Location
iSSTr = iNum & "-" & iLoc 'Sheet String
'Check if OU is West
Select Case iOUT
Case "Central"
'Activate Workbook
iwbSub.Activate
'Add Sheet
On Error Resume Next
Sheets.Add(After:=iwbSub.Sheets(iwbSub.Sheets.Count)).Name = iSSTr
Set iwsTSN = iwbSub.Sheets(iSSTr)
'Activate Sheet
iwsTSN.Activate
'Generate Headers
Range("A1") = "SKU"
Range("B1") = "Status"
Range("C1") = "Description"
'Generate List
With Range("B2:B500").Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="='" & iwsSub.Name & "'!A1:A2"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
'Generate Formula for Description
iwsTSN.Activate
Range("C2") = "=IF(ISBLANK(A2)=TRUE,"""",XLOOKUP(A2," & iwsSub.Name & "!C:C," & iwsSub.Name & "!D:D,"""",0))"
Range("C2").AutoFill Destination:=Range("C2:C500")
End Select
Next iOU
'Save Book
'Activate Workbook
iwbSub.Activate
'Hide List Sheet
On Error Resume Next
iwsSub.Visible = False
'Save Copy
iwbSub.SaveCopyAs iSPth & iwbNew
'Close Submission Book No Save
iwbSub.Close savechanges:=False
'Finalize Report
'Activate Sheet
iwsCS.Activate
'Set Final View
Range("A1").Select
'Completion Message
MsgBox ("Submission Form Generated!")
End Sub
Private Sub M5_Archive_SKUs()
Application.DisplayAlerts = False
'=================================================================================================================================
'Created By Halley Szeto, PI Analyst, Customer Excellence - 9 Jun 21
'Loop to Archive Items based on Rules
'Activate Sheet
iwsDISP1.Activate
'Loop Through SKUs
For Each IArc In Range("A7:A" & Range("A" & Rows.Count).End(xlUp).Row)
'Activate Sheet
iwsDISP1.Activate
'Select and Get Row
IArc.Select
iArcR = IArc.Row
'Save Variables
iODL = UCase(Range("C" & iArcR)) 'Delist Flag
iStat = Range("D" & iArcR) 'Status
iOCt = Application.CountIf(iwsDISP1.Range("E" & iArcR & ":K" & iArcR & ""), "Open") 'Open Count
'Initial Delist Check
Select Case iODL
Case "X" 'Item Delisted
'Check Open Count
Select Case iOCt
Case "0" 'Move
'Import
'Copy
iwsDISP1.Activate
Range("A" & iArcR & ":K" & iArcR).Copy
'Paste Data
iwsDT2.Activate
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Set Date Stamp
Range("L" & Range("A" & Rows.Count).End(xlUp).Row) = Date
'Set Archive Flag
iwsDISP1.Activate
Range("C" & iArcR) = "ARCHIVED"
Case Else 'Still Open in Locations
'No Action
End Select
Case Else 'Not On Delist
'Check Status
Select Case iStat
Case "LTO" 'LTO Status
'Check Open Count
Select Case iOCt
Case 0 'None Open
'Import
'Copy
iwsDISP1.Activate
Range("A" & iArcR & ":K" & iArcR).Copy
'Paste Data
iwsDT2.Activate
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Set Date Stamp
Range("L" & Range("A" & Rows.Count).End(xlUp).Row) = Date
'Set Archive Flag
iwsDISP1.Activate
Range("C" & iArcR) = "ARCHIVED"
Case Else 'Some Locations Open
'No Action
End Select
Case "Long Term OOS", "", " ", 0 'Long Term Out of Stock and Blanks
'Check Open Count
Select Case iOCt
Case 0 'All Closed
'No Action
Case 7 'All Open
'Import
'Copy
iwsDISP1.Activate
Range("A" & iArcR & ":K" & iArcR).Copy
'Paste Data
iwsDT2.Activate
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Set Date Stamp
Range("L" & Range("A" & Rows.Count).End(xlUp).Row) = Date
'Set Archive Flag
iwsDISP1.Activate
Range("C" & iArcR) = "ARCHIVED"
Case Else 'Some location Open
'No Action
End Select
End Select
End Sub
Private Sub S2_Compile_Data()
Application.DisplayAlerts = False
'=================================================================================================================================
'Created By Halley Szeto, PI Analyst, Customer Excellence - 13 May 21
'Compiles Data
'=================================================================================================================================
End Sub
Private Sub S3_Finalize_Report()
Application.DisplayAlerts = False
Dim iDtaRng As Range
'=================================================================================================================================
'Created By Halley Szeto, PI Analyst, Customer Excellence - 13 May 21
'Finalizes Report and Generates Distro Email
'=================================================================================================================================
'Generate Date on Tracker Sheet
'Activate Sheet
iwsDISP1.Activate
Range("C1") = "Current Week " & iFWk
Dim iwbFmt As Workbook
Dim iwsVis As Worksheet
'Generate Copies
'Tracker
'Save Copy As
iwb.SaveCopyAs iSPth & iwbNew1
'Open and Format
'Open Book
Workbooks.Open iSPth & iwbNew1
Set iwbFmt = ActiveWorkbook
'Set View
'Activate Workbook
iwbFmt.Sheets(iwsDISP1.Name).Activate
'Set View
Range("A1").Select
Range("E7").Select
Range("A1").Select
'Hide/Unhide Sheets
'Activate Workbook
iwbFmt.Activate
'Loop and Hide
For Each iwsVis In Worksheets
'Case select set hide/Unhide
Select Case iwsVis.Name
Case iwsDISP1.Name
On Error Resume Next
iwsVis.Visible = True
Case Else
On Error Resume Next
iwsVis.Visible = False
End Select
Next iwsVis
'Save and Close workbook
iwbFmt.Save
iwbFmt.Close savechanges:=True
'Submission Data
'Save Copy As
iwb.SaveCopyAs iSPth & iwbNew2
'Open and Format
'Open Book
Workbooks.Open iSPth & iwbNew2
Set iwbFmt = ActiveWorkbook
'Set View
'Activate Workbook
iwbFmt.Sheets(iwsDT1.Name).Activate
'Set View
Range("A1").Select
'Hide/Unhide Sheets
'Activate Workbook
iwbFmt.Activate
'Loop and Hide
For Each iwsVis In Worksheets
'Case select set hide/Unhide
Select Case iwsVis.Name
Case iwsDT1.Name
On Error Resume Next
iwsVis.Visible = True
Case Else
On Error Resume Next
iwsVis.Visible = False
End Select
Next iwsVis
'Save and Close workbook
iwbFmt.Save
iwbFmt.Close savechanges:=True
'Distribute to Processing if Option Selected
If iEMConf = "Yes" Then
'Activate Sheet
iwsCS.Activate
'Generate To Email
If Range("K" & Rows.Count).End(xlUp).Row > 2 Then
For Each iEM In Range("K3:K" & Range("K" & Rows.Count).End(xlUp).Row)
'Select and Get Row
iEM.Select
iEMRw = iEM.Row
'Generate String
iEMTo = iEMTo & Range("K" & iEMRw) & "; "
Next iEM
Else
iEMTo = ""
End If
'Generate CC Email
If Range("L" & Rows.Count).End(xlUp).Row > 2 Then
For Each iEM In Range("L3:L" & Range("L" & Rows.Count).End(xlUp).Row)
'Select and Get Row
iEM.Select
iEMRw = iEM.Row
'Generate String
iEMCC = iEMCC & Range("L" & iEMRw) & "; "
Next iEM
Else
iEMCC = ""
End If
'Generate Subject Line
iSubj = "Central - Master Data Delist Tracker - " & iDStr
'Generate Body
iMsg = "Hello Everyone," & vbCrLf & vbCrLf & _
"Attached is the delist tracker for " & iDStr & "." & vbCrLf & vbCrLf & _
"Thanks," & vbCrLf
'Generate Email
Dim olApp As Object
Dim olMail As Object
'Set Objects
Set olApp = CreateObject("Outlook.Application")
Set olMail = olApp.CreateItem(olMailItem)
'Generate Email
With olMail
.To = iEMTo
.CC = iEMCC
.Subject = iSubj
.body = iMsg
.Attachments.Add iSPth & iwbNew2
.Display
End With
'Clear Objects
Set olMail = Nothing
Set olApp = Nothing
End If
'Distribute to General Option Selected
If iEMConf1 = "Yes" Then
'Activate Sheet
iwsCS.Activate
'Generate To Email
If Range("I" & Rows.Count).End(xlUp).Row > 2 Then
For Each iEMG In Range("I3:I" & Range("I" & Rows.Count).End(xlUp).Row)
'Select and Get Row
iEMG.Select
iEMRw = iEMG.Row
'Generate String
iEMGTo = iEMGTo & Range("I" & iEMRw) & "; "
Next iEMG
Else
iEMGTo = ""
End If
'Generate CC Email
If Range("J" & Rows.Count).End(xlUp).Row > 2 Then
For Each iEMG In Range("J3:J" & Range("J" & Rows.Count).End(xlUp).Row)
'Select and Get Row
iEMG.Select
iEMRw = iEMG.Row
'Generate String
iEMGCC = iEMGCC & Range("J" & iEMRw) & "; "
Next iEMG
Else
iEMGCC = ""
End If
'Generate Subject Line
iSubjG = "Central - Delist Tracker - " & iDStr
'Generate Body - Depends on If Error items Found
If iErrCt = 0 Then
iMsgG = "Hello Everyone," & "" & "" & _
"Attached is the delist tracker for " & iDStr & "." & "" & "" & _
"Thanks," & ""
Else
iMsgG = "Hello Everyone," & "" & "" & _
"Attached is the delist tracker for " & iDStr & "." & "" & "" & _
"Items were not loaded due to errors detected" & "" & _
"Please review and resubmit the following items:" & "" & "" & _
RangetoHTML(iDtaRng) & "" & "" & "Thanks," & ""
End If
'Generate Email
'Set Objects
Set olApp = CreateObject("Outlook.Application")
Set olMail = olApp.CreateItem(olMailItem)
'Generate Email
With olMail
.To = iEMGTo
.CC = iEMGCC
.Subject = iSubjG
.HTMLbody = iMsgG
.Attachments.Add iSPth & iwbNew1
.Display
End With
'Clear Objects
Set olMail = Nothing
Set olApp = Nothing
End If
End Sub
Private Sub Reconcile()
Application.DisplayAlerts = False
Dim iDtaRng As Range
'=================================================================================================================================
'Created By Halley Szeto, PI Analyst, Customer Excellence - 13 May 21
'Finalizes Report and Generates Distro Email
'=================================================================================================================================
'Save Week
iFWk = iwsCS.Range("D2")
'Execute Reset Call
Call M1_Reset_Sheet
Dim iwbSAP As Workbook
Dim iwsSAP As Worksheet
'Select File to Load
'Set Pathway to Open to
'ChDir ActiveWorkbook.Path
'Run Dialog with Cancellation Error Handling
cancel = Application.GetOpenFilename _
(Title:="Select Central OU Reconcile File to Load")
If cancel = False Then
MsgBox ("Import Session Ended")
Exit Sub
End If
With Workbooks.Open(cancel)
End With
'Set variable Name
Set iwbSAP = ActiveWorkbook
Set iwsSAP = iwbSAP.ActiveSheet
Application.ScreenUpdating = False
Dim iwsTMP1 As Worksheet
'Generate Temp Sheet
'Activate Sheet
iwb.Activate
'Remove Temp Sheet if already exists
On Error Resume Next
iwb.Sheets("TEMP").Delete
'Generate New Sheet
Sheets.Add.Name = "TEMP"
Set iwsTMP1 = iwb.Sheets("TEMP")
'Import Data To Main Sheet
'Copy Data
iwsSAP.Activate
Range("A1:F" & Range("A" & Rows.Count).End(xlUp).Row).Copy
'Paste Data
iwsTMP1.Activate
Range("A1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Close SAP workbook no save
iwbSAP.Close savechanges:=False
'Execute format and clean
'Clean to just relevant Plants and SKUs
'Activate Sheet
iwsTMP1.Activate
'Text to columns material
Columns("D:D").TextToColumns Destination:=Range("D1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
:=Array(1, 1), TrailingMinusNumbers:=True
'Formula Insert and Fill
Range("G2") = "=IF(AND(" & _
"COUNTIFS('" & iwsDISP1.Name & "'!6:6,C2)>0," & _
"COUNTIFS('" & iwsDISP1.Name & "'!A:A,D2)>0)," & _
"""1-KEEP"",""2-DELETE"")"
Range("G2").AutoFill Destination:=Range("G2:G" & Range("A" & Rows.Count).End(xlUp).Row)
Range("G2:G" & Range("A" & Rows.Count).End(xlUp).Row).Copy
Range("G2:G" & Range("A" & Rows.Count).End(xlUp).Row).PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Sort To Group Items for deletion
iwsTMP1.Sort.SortFields.Clear
iwsTMP1.Sort.SortFields.Add2 _
Key:=Range("G2:G" & Range("A" & Rows.Count).End(xlUp).Row), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
With iwsTMP1.Sort
.SetRange Range("A1:G" & Range("A" & Rows.Count).End(xlUp).Row)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Loop and Delete Items
'Set initial Deletion Count
iDelCt = Application.CountIfs(iwsTMP1.Range("G:G"), "2-DELETE")
'Loop Until Deleted
Do Until iDelCt = 0
'Get Start and End Rows
iSRw = Application.Match("2-DELETE", iwsTMP1.Range("G:G"), 0)
iERw = iSRw + (iDelCt - 1)
'Select and Delete Items
Range("G" & iSRw & ":G" & iERw).Select
Range("G" & iSRw & ":G" & iERw).EntireRow.Delete
'ReSet initial Deletion Count
iDelCt = Application.IfError(Application.Match("2-DELETE", iwsTMP1.Range("G:G"), 0), 0)
Loop
'Remove Identifier
Columns("G:G").Delete
'Duplicates Scrub
'Activate sheet
iwsTMP1.Activate
'Generate Duplicates Identifier
Range("G1") = "Unique ID"
Range("H1") = "Duplicates Count"
'Insert Formulas
Range("G2") = "=C2&D2"
Range("H2") = "=IF(COUNTIFS(G:G,G2)>1,""2-DUP"","""")"
Range("G2:H2").AutoFill Destination:=Range("G2:H" & Range("A" & Rows.Count).End(xlUp).Row)
Range("G2:H" & Range("A" & Rows.Count).End(xlUp).Row).Copy
Range("G2:H" & Range("A" & Rows.Count).End(xlUp).Row).PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Duplicates Correction if detected
If Application.CountIfs(iwsTMP1.Range("H:H"), "2-DUP") > 1 Then
'Execute Scrub
'Sort data for Scrub
iwsTMP1.Sort.SortFields.Clear
iwsTMP1.Sort.SortFields.Add2 _
Key:=Range("G2:G" & Range("A" & Rows.Count).End(xlUp).Row), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
With iwsTMP1.Sort
.SetRange Range("A1:H" & Range("A" & Rows.Count).End(xlUp).Row)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Loop and Flag Items for Deletion
'Activate Sheet
iwsTMP1.Activate
'Loop and Execute Ident
For Each iDupCt In Range("H2:H" & Range("A" & Rows.Count).End(xlUp).Row)
'Select and Get row
iDupCt.Select
iDCRw = iDupCt.Row
'Save Start and End Rows
iUIDS = Range("G" & iDCRw)
iDRS = Application.Match(iUIDS, iwsTMP1.Range("G:G"), 0)
iDRE = iDRS + (Application.CountIfs(iwsTMP1.Range("G:G"),iUIDS)−1)E" & iDCRw), iwsTMP1.Range("E" & iDRS & ":E" & iDRE), 0) > 1 Then
Range("H" & iDCRw) = "2-DELETE"
Else
Range("H" & iDCRw) = "1-KEEP"
End If
Next iDupCt
'Sort and Delete all Items flagged for deletion
'Activate Sheet
iwsTMP1.Activate
'Sort Items for Deletion Groups
iwsTMP1.Sort.SortFields.Clear
iwsTMP1.Sort.SortFields.Add2 _
Key:=Range("H2:H" & Range("A" & Rows.Count).End(xlUp).Row), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
With iwsTMP1.Sort
.SetRange Range("A1:H" & Range("A" & Rows.Count).End(xlUp).Row)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'Loop and Delete Items
'Set initial Deletion Count
iDelCt = Application.CountIfs(iwsTMP1.Range("H:H"), "2-DELETE")
'Loop Until Deleted
Do Until iDelCt = 0
'Get Start and End Rows
iSRw = Application.Match("2-DELETE", iwsTMP1.Range("H:H"), 0)
iERw = iSRw + (iDelCt - 1)
'Select and Delete Items
Range("H" & iSRw & ":H" & iERw).Select
Range("H" & iSRw & ":H" & iERw).EntireRow.Delete
'ReSet initial Deletion Count
iDelCt = Application.IfError(Application.Match("2-DELETE", iwsTMP1.Range("H:H"), 0), 0)
Loop
End If
'Identify Status
'Reset Columns
Columns("G:H").Delete
Range("G1") = "Status"
'Generate Formula
Range("G2") = "=IF(YEAR($F2)=9999,""Unblock"",""Block"")"
Range("G2").AutoFill Destination:=Range("G2:G" & Range("A" & Rows.Count).End(xlUp).Row)
Range("G2:G" & Range("A" & Rows.Count).End(xlUp).Row).Copy
Range("G2:G" & Range("A" & Rows.Count).End(xlUp).Row).PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Resort Data
Columns("C:C").Cut
Columns("A:A").Insert
Columns("G:G").Cut
Columns("A:A").Insert
Columns("E:E").Cut
Columns("A:A").Insert
'Import data to Submitted SKUs Sheet
iwsTMP1.Activate
Range("A2:C" & Range("A" & Rows.Count).End(xlUp).Row).Copy
iwsDT1.Activate
Range("A2").PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Delete Temp Sheet
iwsTMP1.Delete
'Loop Through Each SKU and set tracker
'Replicate Actions
'Loop Through Replicate Actions Database
'Activate Sheet
iwsCS.Activate
'Generate Temp Sheet
'Remove Temp Sheet if Pre Existing
On Error Resume Next
iwb.Sheets("TEMP").Delete
'Generate New Temp Sheet
Dim iwsTMP As Worksheet
Sheets.Add.Name = "TEMP"
Set iwsTMP = iwb.Sheets("TEMP")
'Generate Headers
iwsTMP.Activate
Range("A1") = "SKU"
Range("B1") = "Status"
Range("C1") = "Plant"
'Activate Sheet
iwsCS.Activate
'Execute Loop and Search
For Each iRA In Range("AB3:AB" & Range("AB" & Rows.Count).End(xlUp).Row)
'Activate Sheet
iwsCS.Activate
'Select and Save Data
iRA.Select
iRAR = iRA.Row
iFP = Range("AB" & iRAR)
iTP = Range("AC" & iRAR)
'Execute Loop in Submitted SKUs
'Activate Sheet
iwsDT1.Activate
'Loop
For Each iCK In Range("C2:C" & Range("A" & Rows.Count).End(xlUp).Row)
'Activate Sheet
iwsDT1.Activate
'Save Variables
iCK.Select
iCKR = iCK.Row
iPlt = Range("C" & iCKR)
'Check if Replication Required
If iPlt = iFP Then
'Save Data
iSKU = Range("A" & iCKR)
iStat = Range("B" & iCKR)
'Set Temp Row
iwsTMP.Activate
iTMPR = Application.Range("A" & Rows.Count).End(xlUp).Row + 1
'Insert Data
Range("A" & iTMPR) = iSKU
Range("B" & iTMPR) = iStat
Range("C" & iTMPR) = iTP
End If
Next iCK
Next iRA
'Move Data Back to Data Sheet
'Activate Sheet
iwsTMP.Activate
'Check if Import Required
If Range("A" & Rows.Count).End(xlUp).Row > 1 Then
'Copy Data
iwsTMP.Activate
Range("A2:C" & Range("A" & Rows.Count).End(xlUp).Row).Copy
'Paste Data
iwsDT1.Activate
Range("A" & Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End If
'Delete Temp Sheet
On Error Resume Next
iwsTMP.Delete
'Update Tracker
'Activate Sheet
iwsDT1.Activate
'Loop
For Each iSKU In Range("A2:A" & Range("A" & Rows.Count).End(xlUp).Row)
'Activate Sheet
iwsDT1.Activate
'Select and get Data
iSKU.Select
iSRw = iSKU.Row
'Save data Sheet Variables
'Activate Sheet
iwsDT1.Activate
'Set Variables
iSKUN = Range("A" & iSRw) 'SKU
iStat = Range("B" & iSRw) 'Status
iPlnt = Range("C" & iSRw) 'Plant
'Set Tracker
'Activate Sheet
iwsDISP1.Activate
'Check if New Item - Skip
If Application.IfError(Application.Match(iSKUN, iwsDISP1.Range("A:A"), 0), 0) = 0 Then
GoTo iSkipProcess
Else
'Set Working Row
iWRw = Application.Match(iSKUN, iwsDISP1.Range("A:A"), 0)
End If
'Set Column/Range Variable
'Working Column
'Get Working Column
iWCol = Application.IfError(Application.Match(iPlnt, iwsDISP1.Rows("6:6"), 0), 0)
'Error Handler
If iWCol = 0 Then
GoTo iSkipProcess
Else
'Convert Column Number to Letter
iWCol = Left(Right(Cells(1, iWCol).Address, _
Len(Cells(1, iWCol).Address) - 1), _
Application.Search("$", Right(Cells(1, iWCol).Address, _
Len(Cells(1, iWCol).Address) - 1)) - 1)
End If
'Working Range
Dim iWRng As Range
Set iWRng = Range(iWCol & iWRw)
iWRng.Select
'Set Block/Unblock
Select Case iStat
Case "Block"
'Activate Sheet
iwsDISP1.Activate
'Set Week
iWRng = "Block"
'Set Formatting
'Highlight
With iWRng.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'Font
With iWRng.Font
.Color = -16776961
.TintAndShade = 0
End With
Case "Unblock"
'Activate Sheet
iwsDISP1.Activate
'Set Open
iWRng = "Unblock"
'Set Formatting
'Highlight
With iWRng.Interior
.Pattern = xlNone
.TintAndShade = 0
.PatternTintAndShade = 0
End With
'Font
With iWRng.Font
.Color = -16776961
.TintAndShade = 0
End With
End Select
iSkipProcess:
Next iSKU
'Completion Message
Application.ScreenUpdating = False
MsgBox ("Mass System Reconciliation Complete!")
End Sub
Function RangetoHTML(rng As Range)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
'Create Temp File
TempFile = Environ$("temp") & "" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
'Copy the range and create a new workbook to past the data in
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
'Publish the sheet to a htm file
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
'Read all data from the htm file into RangetoHTML
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
The provided code is a collection of VBA (Visual Basic for Applications) subroutines and a function designed to manage SKU (Stock Keeping Unit) blocking and unblocking within an Excel workbook. This code is likely used in an inventory management context to track product availability across different plants or locations.
Below is an explanation of each subroutine and function, including their purpose and key operations:
Subroutine: M1_Reset_Sheet
Purpose:
Resets specific sheets in the workbook to their initial state, preparing them for new data entry or processing.
Key Operations:
User Confirmation:
Displays a message box asking the user to confirm if they want to proceed with resetting the sheets.
If the user selects "No," the subroutine exits.
Reset Data SKUs Sheet (iwsDT1):
Activates the Data SKUs sheet.
Deletes all existing data except for the headers.
Resets headers in cells A1:C1 to "SKU," "Status," and "Plant."
Sets up data validation (dropdown list) for the "Status" column (B2:B1000) with options from another sheet (iwsCS).
Reset Tracker Sheet (iwsDISP1):
Activates the Tracker sheet.
Resets the font color for a specific range to default.
Iterates through specified columns to find and update the status of SKUs:
Changes cells with "Unblock" to "Open" and applies green formatting.
Changes cells with "Block" to "Closed."
Reset Error Report (iwsDISP2):
Activates the Error Report sheet.
Deletes all existing data and resets the headers to default.
Finalize:
Activates key sheets and selects cell A1 in each for a clean view.
Displays a message box confirming that the sheets have been reset.
Subroutine: M2_Load_Submission_Data
Purpose:
Loads SKU blocking/unblocking data from an external submission file into the Data SKUs sheet.
Key Operations:
File Selection:
Prompts the user to select a "Central OU Submission Form" file to load.
If the user cancels, the subroutine exits.
Data Import:
Opens the selected workbook (iwbSub).
Iterates through all worksheets in the opened workbook.
For each worksheet:
Skips sheets named "List."
Extracts the location code (first four characters of the sheet name).
Checks if the location is valid by matching it against reference lists in the Control Sheet (iwsCS).
If valid and contains data, copies the SKU data (A2:B...) into the Data SKUs sheet (iwsDT1).
Populates the "Plant" column with the location code.
Cleanup:
Closes the imported workbook without saving changes.
Activates key sheets and selects cell A1 in each.
Displays a message box confirming that the submission data has been loaded.
Subroutine: M3_Compile_Report
Purpose:
Manages the process of compiling data and finalizing the report based on user input.
Key Operations:
User Selection:
Prompts the user to select an action:
1 - Run all (compile data and finalize report).
2 - Compile data only.
3 - Finalize report only.
0 - Cancel operation.
Validates the user's input.
Action Execution:
Depending on the selection, calls the appropriate subroutines:
S2_Compile_Data for compiling data.
S3_Finalize_Report for finalizing the report.
Validation Checks:
Ensures the fiscal week and save path are correctly set in the Control Sheet.
If invalid entries are found, displays an error message and exits.
Finalize:
Activates the Control Sheet and selects cell A1.
Displays a completion message, including a warning if there are items in the error report.
Subroutine: M4_Generate_Submission_Form
Purpose:
Generates a submission form workbook with individual sheets for plants requiring SKU status updates.
Key Operations:
Variables Setup:
Determines the save path and constructs date strings for file naming.
Sets the name for the new workbook (iwbNew).
New Workbook Creation:
Creates a new workbook (iwbSub) and adds a "List" sheet containing "Block" and "Unblock" options.
Copies SKU descriptions and other relevant data from a reference sheet (iwsCFT1) into the "List" sheet.
Plant Sheets Generation:
Iterates through operating units (OUs) listed in the Control Sheet (iwsCS).
For each OU in the "Central" region:
Adds a new sheet named with the plant number and location code.
Sets up headers and data validation for SKU status.
Adds formulas to pull the SKU description based on the entered SKU number.
Saving the Submission Form:
Hides the "List" sheet in the workbook.
Saves the workbook to the specified path with the constructed filename.
Finalize:
Activates the Control Sheet and selects cell A1.
Displays a message confirming that the submission form has been generated.
Subroutine: M5_Archive_SKUs
Purpose:
Archives SKUs that meet certain conditions (e.g., delisted, long-term out-of-stock) and cleans up the tracker.
Key Operations:
Archiving SKUs:
Iterates through SKUs in the Tracker sheet (iwsDISP1).
For each SKU, determines whether it should be archived based on:
Delist flags.
Product status.
Whether all locations have the SKU marked as "Closed" or "Open."
Moves SKUs to the Archived SKUs sheet (iwsDT2) if they meet the criteria.
Marks archived SKUs with the date and updates their status in the Tracker sheet.
Cleanup:
Deletes archived SKUs from the Tracker sheet.
In the Archived SKUs sheet, identifies entries older than 90 days and deletes them.
Ensures the date sorting is maintained in the Archived SKUs sheet.
Finalize:
Activates the Tracker sheet and selects cell A1.
Displays a message confirming that SKU archival is complete.
Subroutine: S2_Compile_Data
Purpose:
Compiles and processes SKU data, applies business rules, and updates the Tracker sheet accordingly.
Key Operations:
Setup:
Retrieves the fiscal week from the Control Sheet.
Refreshes data connections in the CRAFT sheet (iwsCFT1).
Corrects SKU formats in the Data SKUs sheet (iwsDT1) to ensure consistency.
Applying Replication Rules:
Uses replication rules defined in the Control Sheet to replicate actions across different plants.
For plants that require replication, additional entries are created in the Data SKUs sheet.
Data Scrubbing:
Removes duplicates where SKUs have the same status and plant.
Identifies and handles duplicates with different statuses by moving conflicting entries to the Error Report sheet (iwsDISP2).
Validates the "Status" and "Plant" entries against predefined lists in the Control Sheet.
Checks for SKUs that should be excluded based on a list in the Control Sheet.
Updating the Tracker:
Iterates through each SKU in the Data SKUs sheet.
Updates the Tracker sheet (iwsDISP1) by marking the SKU status for each relevant plant.
Formats cells to visually represent the SKU status (e.g., color coding "Block" and "Unblock").
Final Formatting:
Cleans up the Tracker sheet by filling in blanks and ensuring consistent formatting.
Updates SKU descriptions if necessary.
Subroutine: S3_Finalize_Report
Purpose:
Finalizes the report by saving copies of key sheets and optionally generating emails to distribute the reports.
Key Operations:
Saving Reports:
Saves copies of the Tracker and Submission Data sheets to specified paths with date-stamped filenames.
Opens each saved workbook to format and hide unnecessary sheets before saving.
Email Distribution:
Checks user settings in the Control Sheet to determine if emails should be sent.
Constructs email content, including recipients, subject lines, and body messages.
If errors were found during data compilation, includes an HTML-formatted table of errors in the email body using the RangetoHTML function.
Uses Outlook to generate emails with the finalized reports attached.
Subroutine: Reconcile
Purpose:
Performs a mass system reconciliation by resetting sheets and importing data from a SAP reconciliation file.
Key Operations:
Setup:
Calls M1_Reset_Sheet to reset the workbook to its initial state.
Data Import:
Prompts the user to select a "Central OU Reconcile File" to load.
Imports the data into a temporary sheet (iwsTMP1) for processing.
Data Processing:
Formats and cleans the imported data to keep only relevant SKUs and plants.
Removes duplicates and identifies the current status (Block/Unblock) for each SKU.
Updates the Data SKUs sheet (iwsDT1) with the processed data.
Tracker Update:
Applies replication rules as defined in the Control Sheet.
Updates the Tracker sheet (iwsDISP1) based on the reconciled data.
Finalize:
Displays a message confirming that the mass system reconciliation is complete.
Function: RangetoHTML
Purpose:
Converts a given Excel range into an HTML format suitable for inclusion in an email body.
Key Operations:
Temporary File Creation:
Copies the specified range and pastes it into a new temporary workbook.
Saves the workbook as an HTML file in the user's temporary directory.
HTML Extraction:
Reads the content of the HTML file into a string variable (RangetoHTML).
Modifies the HTML content to adjust alignment as needed.
Cleanup:
Closes and deletes the temporary workbook and HTML file.
Returns the HTML-formatted string.
Additional Notes:
Variable Naming Conventions:
Variables starting with i (e.g., iwsDT1, iDelCt) are often used as counters or indices.
iwb refers to the main workbook, while iwbSub, iwbFmt, and others refer to newly created or opened workbooks.
iws variables represent worksheet objects.
Error Handling:
The code uses On Error Resume Next to handle potential runtime errors without stopping execution.
After critical operations, it checks for errors and displays messages to the user if necessary.
User Interaction:
Throughout the code, message boxes are used to communicate with the user for confirmations, errors, and completion messages.
Input boxes are used to get user selections for certain operations.
Data Validation and Formatting:
Data validation is applied to ensure that only valid entries are made in certain cells.
Conditional formatting and cell styling are used to enhance the visual representation of the data.
Email Automation:
Uses Outlook Application objects to automate the creation and sending of emails.
Constructs emails based on templates and user selections, attaching necessary files.
This explanation provides an overview of the code's functionality and the key operations performed within each subroutine and function. If you need further clarification on specific parts of the code or how certain variables are used, feel free to ask!