I have a code which works for creating unique code for box packing 2 subjects book together in one box where number of books does not exceed 400. The packing must contain 2 subjects within same school and same distribution centre. It also exclude books with qty greater than 200.
Now I have to revise code for 4 subjects book & 6 subject book but the condition of packing remaining same as 400 per box and now exclude more than 100 (if 4 subjects) & exclude more than 66 (if 6 subjects).
Please help modifying the code.
'''
Option Explicit
Sub GenerateUniqueCode_Stage1()
Dim ws As Worksheet
Dim lastRow As Long
Dim distCenterCol As Range, schoolCol As Range, quantityCol As Range, subjectCol As Range, codeCol As Range
Dim boxCounter As Long
Dim prevDistCenter As String
Dim boxCode As String
Dim totalBooks As Long
Dim boxSubjects As String
Dim i As Long
' Set the worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
' Find the last row with data in column E
lastRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).Row
' Set the ranges for the columns
Set distCenterCol = ws.Range("E2:E" & lastRow)
Set schoolCol = ws.Range("G2:G" & lastRow)
Set quantityCol = ws.Range("H2:H" & lastRow)
Set subjectCol = ws.Range("I2:I" & lastRow)
Set codeCol = ws.Range("K2:K" & lastRow)
' Initialize variables
boxCounter = 1
prevDistCenter = distCenterCol.Cells(2).Value
boxCode = "BOX-" & Format(boxCounter, "000")
totalBooks = 0
boxSubjects = ""
' Loop through each row in the data
Dim j As Long, schoolBooks As Long, remainingBooks As Long
Dim distCenter As String, School As String, Subject As String
For i = 1 To lastRow - 1
distCenter = distCenterCol.Cells(i).Value
School = schoolCol.Cells(i).Value
Subject = subjectCol.Cells(i).Value
remainingBooks = quantityCol.Cells(i).Value
schoolBooks = remainingBooks
' Exclude schools with quantity 100 or more
If remainingBooks >= 100 Then
codeCol.Cells(i).Value = "Excluded"
Else
For j = i + 1 To lastRow
If prevDistCenter = distCenterCol.Cells(j).Value And _
School = schoolCol.Cells(j).Value And _
quantityCol.Cells(j).Value < 100 Then
schoolBooks = schoolBooks + quantityCol.Cells(j).Value
Else
Exit For
End If
Next
' Check if distribution center changes or adding the books exceeds the box limit
If distCenter <> prevDistCenter Or totalBooks + schoolBooks > 300 Or _
(InStr(1, boxSubjects, "English") = 0 And _
InStr(1, boxSubjects, "Social & Religious Studies") = 0) Then
' Start a new box
boxCounter = boxCounter + 1
boxCode = Left(distCenter, 3) & "BOXENGSOC" & Format(boxCounter, "000")
totalBooks = remainingBooks
boxSubjects = Subject
Else
totalBooks = totalBooks + remainingBooks
boxSubjects = boxSubjects & ", " & Subject
End If
' Update the box code in column K
codeCol.Cells(i).Value = boxCode
' Update the previous distribution center
prevDistCenter = distCenter
End If
Next i
End Sub
'''
[![Sample][1]][1]
[1]: https://i.sstatic.net/TpKRa5mJ.png