' VBA Code to Initialize Workbook and Generate Task Tracker
' Place this code in a standard module (Insert > Module) in the VBA editor.
Option Explicit
' Subroutine to initialize the workbook: create sheets, set up columns, add button
Sub InitializeTaskTracker()
Dim wsTaskTracker As Worksheet
Dim wsSettings As Worksheet
Dim shp As Shape
Dim btnLeft As Double, btnTop As Double, btnWidth As Double, btnHeight As Double
Dim btnName As String
code
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Attempt to set Task Tracker sheet; if it doesn't exist, create it
On Error Resume Next
Set wsTaskTracker = ThisWorkbook.Worksheets("Task Tracker")
On Error GoTo 0
If wsTaskTracker Is Nothing Then
Set wsTaskTracker = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
wsTaskTracker.Name = "Task Tracker"
Else
' Clear existing content
wsTaskTracker.Cells.Clear
End If
' Attempt to set Settings sheet; if it doesn't exist, create it
On Error Resume Next
Set wsSettings = ThisWorkbook.Worksheets("Settings")
On Error GoTo 0
If wsSettings Is Nothing Then
Set wsSettings = ThisWorkbook.Worksheets.Add(After:=wsTaskTracker)
wsSettings.Name = "Settings"
Else
' Clear existing content
wsSettings.Cells.Clear
End If
' Set up columns in Task Tracker
With wsTaskTracker
.Range("A1").Value = "Date Offered"
.Range("B1").Value = "Date Completed"
.Range("C1").Value = "Time Started"
.Range("D1").Value = "Time Finished"
.Range("E1").Value = "Duration (mins)"
.Range("F1").Value = "Reference Number"
.Range("G1").Value = "Function/Job Classification"
.Range("H1").Value = "Remarks/Notes"
' Format header as bold and apply background color
With .Range("A1:H1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:H").AutoFit
End With
' Set up Settings sheet
With wsSettings
' Define parameters and labels
.Range("A1").Value = "Parameter"
.Range("B1").Value = "Value"
.Range("A2").Value = "Start Time (m/d/yyyy h:mm AM/PM)"
' Example: 10/5/2023 8:00 AM (User should modify as needed)
.Range("B2").Value = "10/5/2023 8:00 AM"
.Range("A3").Value = "First Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B3").Value = "10/5/2023 10:00 AM"
.Range("A4").Value = "First Break Duration (mins)"
.Range("B4").Value = 13
.Range("A5").Value = "Lunch Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B5").Value = "10/5/2023 12:30 PM"
.Range("A6").Value = "Lunch Break Duration (mins)"
.Range("B6").Value = 55
.Range("A7").Value = "Last Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B7").Value = "10/5/2023 3:30 PM"
.Range("A8").Value = "Last Break Duration (mins)"
.Range("B8").Value = 15
' Headers for Org Codes, Functions, and Remarks
.Range("C9").Value = "Org Codes"
.Range("D9").Value = "Function/Job Classification"
.Range("E9").Value = "Remarks/Notes"
With .Range("C9:E9")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Example Org Codes
.Range("C10").Value = "ORG001"
.Range("C11").Value = "ORG002"
.Range("C12").Value = "ORG003"
' Add more Org Codes as needed
' Example Functions and Remarks
.Range("D10").Value = "Checking Organization Records"
.Range("D11").Value = "Creating Organization Records"
.Range("D12").Value = "Email Management"
.Range("D13").Value = "PowerBi"
.Range("D14").Value = "Updating Organization"
.Range("D15").Value = "Uploading Edocs"
.Range("D16").Value = "Verifying Temporary Accounts"
.Range("D17").Value = "OBPI Adhoc"
.Range("E10").Value = "Remark for Checking Organization Records"
.Range("E11").Value = "Remark for Creating Organization Records"
.Range("E12").Value = "Remark for Email Management"
.Range("E13").Value = "Remark for PowerBi"
.Range("E14").Value = "Remark for Updating Organization"
.Range("E15").Value = "Remark for Uploading Edocs"
.Range("E16").Value = "Remark for Verifying Temporary Accounts"
.Range("E17").Value = "Remark for OBPI Adhoc"
' Add more Remarks as needed
' Format headers for Parameter
With .Range("A1:B1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:E").AutoFit
End With
' Remove existing "Generate Tasks" button if it exists
btnName = "btnGenerateTasks"
On Error Resume Next
wsTaskTracker.Shapes(btnName).Delete
On Error GoTo 0
' Add a button to Task Tracker sheet to run GenerateTasks macro using Shapes.AddFormControl
With wsTaskTracker
' Define button dimensions and position
btnLeft = 10
btnTop = 10
btnWidth = 120
btnHeight = 30
' Add the button as a Form Control
Set shp = .Shapes.AddFormControl(Type:=xlButtonControl, Left:=btnLeft, Top:=btnTop, Width:=btnWidth, Height:=btnHeight)
With shp
.OnAction = "GenerateTasks"
.Name = btnName
.TextFrame.Characters.Text = "Generate Tasks"
.TextFrame.HorizontalAlignment = xlHAlignCenter
.TextFrame.VerticalAlignment = xlVAlignCenter
.Fill.ForeColor.RGB = RGB(0, 112, 192) ' Optional: Button color
.Fill.Transparency = 0
.Line.Visible = msoFalse ' Optional: Remove button border
.TextFrame.Characters.Font.Color = RGB(255, 255, 255) ' Optional: Text color
.TextFrame.Characters.Font.Bold = True
End With
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Workbook initialized successfully! Please configure the 'Settings' sheet before generating tasks.", vbInformation
End Sub
' Subroutine to generate tasks based on Settings
Sub GenerateTasks()
Dim wsTracker As Worksheet
Dim wsSettings As Worksheet
code
ContinueLoop:
Loop
code
' Optionally, format the Task Tracker sheet
With wsTracker
.Columns("A:H").AutoFit
' Format columns A, B as Date/Time and C, D as Time
.Columns("A").NumberFormat = "m/d/yyyy h:mm AM/PM"
.Columns("B").NumberFormat = "m/d/yyyy h:mm AM/PM"
.Columns("C").NumberFormat = "h:mm AM/PM"
.Columns("D").NumberFormat = "h:mm AM/PM"
End With
MsgBox "Tasks generated successfully in the 'Task Tracker' sheet.", vbInformation
End Sub
' Function to get Org Codes from a column starting from a specific row
Function GetOrgCodes(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim orgCodes As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
orgCodes.Add ws.Cells(i, col).Value
End If
Next i
Set GetOrgCodes = orgCodes
End Function
' Function to get Functions from a column starting from a specific row
Function GetFunctionsList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim funcList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
funcList.Add ws.Cells(i, col).Value
End If
Next i
Set GetFunctionsList = funcList
End Function
' Function to get Remarks from a column starting from a specific row
Function GetRemarksList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim remarksList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
remarksList.Add ws.Cells(i, col).Value
End If
Next i
Set GetRemarksList = remarksList
End Function
' Function to perform weighted random selection
' probabilities array contains weights
' numTasks is the number of tasks
Function GetWeightedRandomTaskIndex(probabilities As Variant, numTasks As Integer) As Integer
Dim totalWeight As Double
Dim i As Integer
totalWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
totalWeight = totalWeight + probabilities(i)
Next i
code
Dim randVal As Double
randVal = Rnd * totalWeight
Dim cumulativeWeight As Double
cumulativeWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
cumulativeWeight = cumulativeWeight + probabilities(i)
If randVal <= cumulativeWeight Then
GetWeightedRandomTaskIndex = i
Exit Function
End If
Next i
' In case of rounding errors
GetWeightedRandomTaskIndex = UBound(probabilities)
End Function
' Function to get Remark for a given Function
Function GetRemarkForFunction(ws As Worksheet, funcCol As Integer, remarkCol As Integer, functionName As String) As String
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, funcCol).End(xlUp).Row
Dim i As Long
For i = 10 To lastRow ' Starting from row 10
If Trim(ws.Cells(i, funcCol).Value) = Trim(functionName) Then
GetRemarkForFunction = ws.Cells(i, remarkCol).Value
Exit Function
End If
Next i
' If not found, return empty string
GetRemarkForFunction = ""
End Function
everything is correct except the date offered, date completed, time started, time finished and the generated times not including the milisecond. so for my request below edit only the codes that will be affected.
analyze this code for my excel tracker please edit it the date offere and the date completed should display dates only no time like this 10/5/2023 and the date offered should be the same date as the time started of its corresponding row. also the time started and time completed should be in this format 9/5/2024 8:56:30 AM . also exept the very first time started cause it should use the time in in the settings, for the time started of the next row it should use the time finished from the first row with additional of randomly between 1-3 seconds on its time so for example on the first row the time finished is 10/5/2023 8:03:00 AM in the next row the time started should use this time with addtional of random times within 1-3 seconds.
send me the entire complete updated vba code
also can you make the tracker to generate time including the miliseconds and incorporate that also in the duration
Assistant
Below is the updated VBA code that incorporates your requests. Changes have been made to the subroutines and functions that handle date and time formatting, as well as the addition of random milliseconds:
The error you're encountering likely stems from an issue with how time calculations are being conducted when working with milliseconds. To resolve it, make sure that time manipulation is correctly calculated using DateAdd rather than directly in arithmetic to properly handle time in Excel VBA. Let's adjust the code accordingly:
Here is the corrected version of the task duration calculation that uses DateAdd for handling smaller time increments:
vba
User
resend the entire complete updated code
Assistant
Below is the complete and updated VBA code with changes applied to handle milliseconds correctly for time calculations, ensuring that the dates, times, and durations function as required:
vba
User
can you make the format of the duration to be displayed like this
12:01:00 AM
also the miliseconds in the durations is not reflected in time started and finished sample output below
10/5/2023 10/5/2023 10/5/2023 8:00:00.000 AM 10/5/2023 8:02:00.000 AM 2.817
10/5/2023 10/5/2023 10/5/2023 8:02:02.000 AM 10/5/2023 8:04:02.000 AM 2.798
10/5/2023 10/5/2023 10/5/2023 8:04:04.000 AM 10/5/2023 8:05:04.000 AM 1.25
see the first row says 2.817 mins but the time started and finished only reflects 2 mins interval
Assistant
To ensure that the duration reflects the correct difference between the Time Started and Time Finished (including milliseconds), we need to revisit how the Time Finished values are calculated. Additionally, I will modify the code to display the duration with a "h:mm:ss AM/PM" format.
Here's how you can update your VBA code to reflect these changes:
vba
User
this is sample output
10/5/2023 10/5/2023 10/5/2023 8:00:00.000 AM 10/5/2023 8:03:00.000 AM
10/5/2023 10/5/2023 10/5/2023 8:03:02.000 AM 10/5/2023 8:05:02.000 AM
10/5/2023 10/5/2023 10/5/2023 8:05:04.000 AM 10/5/2023 8:08:04.000 AM
can you make the tracker generate time using milliseconds so that the random times used are not excatly perminute just like in the sammple below compare the time started and finished from the ouput of the code to the sample below
9/5/2024 9/5/2024 9/5/2024 3:10:58 AM 9/5/2024 3:11:42 AM
9/5/2024 9/5/2024 9/5/2024 3:11:43 AM 9/5/2024 3:12:31 AM
9/5/2024 9/5/2024 9/5/2024 3:12:32 AM 9/5/2024 3:14:18 AM
9/5/2024 9/5/2024 9/5/2024 3:14:19 AM 9/5/2024 3:15:22 AM
9/5/2024 9/5/2024 9/5/2024 3:15:23 AM 9/5/2024 3:16:17 AM
also please follow the logic of the below code for the random time range and probability of choosing for each task
' VBA Code to Initialize Workbook and Generate Task Tracker
' Place this code in a standard module (Insert > Module) in the VBA editor.
Option Explicit
' Subroutine to initialize the workbook: create sheets, set up columns, add button
Sub InitializeTaskTracker()
Dim wsTaskTracker As Worksheet
Dim wsSettings As Worksheet
Dim shp As Shape
Dim btnLeft As Double, btnTop As Double, btnWidth As Double, btnHeight As Double
Dim btnName As String
code
Assistant
To create a task tracker with precise time intervals including milliseconds, and match the logic and structure from your sample code, we'll carefully update the subroutine to ensure randomness in durations and incorporate milliseconds correctly. Let's enhance the VBA code:
vba
User
now I just need the duration to be displayed in this format
12:03:00 AM
Assistant
To display the duration in the "hh:mm:ss AM/PM" format, we need to ensure the calculation of the task duration is properly formatted in this manner. This requires converting the duration from fractional minutes into a time value that Excel can format directly as you requested. Here's how you can achieve that:
Set wsTracker = ThisWorkbook.Worksheets("Task Tracker")
Set wsSettings = ThisWorkbook.Worksheets("Settings")
' Read Start Time
Dim startTime As Date
If IsDate(wsSettings.Range("B2").Value) Then
startTime = wsSettings.Range("B2").Value
Else
MsgBox "Please enter a valid Start Time in the 'Settings' sheet (cell B2).", vbExclamation
Exit Sub
End If
' Read Break Start Times and Durations
Dim break1Start As Date, break1Duration As Double
Dim lunchBreakStart As Date, lunchBreakDuration As Double
Dim break2Start As Date, break2Duration As Double
If IsDate(wsSettings.Range("B3").Value) Then
break1Start = wsSettings.Range("B3").Value
Else
MsgBox "Please enter a valid First Break Start Time in the 'Settings' sheet (cell B3).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B4").Value) Then
break1Duration = wsSettings.Range("B4").Value
Else
MsgBox "Please enter a valid First Break Duration in minutes in the 'Settings' sheet (cell B4).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B5").Value) Then
lunchBreakStart = wsSettings.Range("B5").Value
Else
MsgBox "Please enter a valid Lunch Break Start Time in the 'Settings' sheet (cell B5).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B6").Value) Then
lunchBreakDuration = wsSettings.Range("B6").Value
Else
MsgBox "Please enter a valid Lunch Break Duration in minutes in the 'Settings' sheet (cell B6).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B7").Value) Then
break2Start = wsSettings.Range("B7").Value
Else
MsgBox "Please enter a valid Last Break Start Time in the 'Settings' sheet (cell B7).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B8").Value) Then
break2Duration = wsSettings.Range("B8").Value
Else
MsgBox "Please enter a valid Last Break Duration in minutes in the 'Settings' sheet (cell B8).", vbExclamation
Exit Sub
End If
' Read Org Codes from Settings, Column C, starting from C10 down
Dim orgCodes As Collection
Set orgCodes = GetOrgCodes(wsSettings, 3, 10) ' Column C, starting from row 10
If orgCodes.Count = 0 Then
MsgBox "Please enter at least one Org Code in the 'Settings' sheet (column C starting from row 10).", vbExclamation
Exit Sub
End If
' Read Functions and Remarks from Settings, Columns D and E, starting from D10 and E10
Dim functionsList As Collection
Dim remarksList As Collection
Set functionsList = GetFunctionsList(wsSettings, 4, 10) ' Column D
Set remarksList = GetRemarksList(wsSettings, 5, 10) ' Column E
If functionsList.Count = 0 Then
MsgBox "Please enter at least one Function/Job Classification in the 'Settings' sheet (column D starting from row 10).", vbExclamation
Exit Sub
End If
If remarksList.Count = 0 Then
MsgBox "Please enter at least one Remark/Notes in the 'Settings' sheet (column E starting from row 10).", vbExclamation
Exit Sub
End If
' Define tasks with their probabilities and duration ranges
' Ensure that the number of tasks matches the entries in Settings
Dim taskNames As Variant
Dim taskWeights As Variant
Dim taskMinDurations As Variant
Dim taskMaxDurations As Variant
Dim numTasks As Integer
' Initialize task arrays
taskNames = Array("Checking Organization Records", "Creating Organization Records", "Email Management", _
"PowerBi", "Updating Organization", "Uploading Edocs", "Verifying Temporary Accounts", "OBPI Adhoc")
taskWeights = Array(80, 10, 80, 40, 30, 60, 80, 10) ' Corresponding to weights
taskMinDurations = Array(1, 10, 2, 2, 5, 1, 1, 10)
taskMaxDurations = Array(3, 12, 3, 3, 6, 2, 2, 20)
numTasks = UBound(taskNames) - LBound(taskNames) + 1
' Validate that task arrays align with Settings entries
If numTasks <> functionsList.Count Or numTasks <> remarksList.Count Then
MsgBox "Mismatch between defined tasks and Settings entries. Please ensure they align.", vbExclamation
Exit Sub
End If
' Define total desired duration in minutes (7 hrs 30 mins to 7 hrs 35 mins)
Dim minTotalDuration As Double, maxTotalDuration As Double
minTotalDuration = 450 ' 7*60 + 30
maxTotalDuration = 455 ' 7*60 + 35
' Initialize variables for task generation
Dim currentTime As Date
currentTime = startTime
Dim totalDuration As Double
totalDuration = 0
' Define Breaks as arrays
Dim breakStarts(1 To 3) As Date
Dim breakDurations(1 To 3) As Double
breakStarts(1) = break1Start
breakDurations(1) = break1Duration
breakStarts(2) = lunchBreakStart
breakDurations(2) = lunchBreakDuration
breakStarts(3) = break2Start
breakDurations(3) = break2Duration
' Sort breaks by start time in ascending order
Dim i As Integer, j As Integer
Dim tempStart As Date, tempDuration As Double
For i = 1 To 2
For j = i + 1 To 3
If breakStarts(i) > breakStarts(j) Then
tempStart = breakStarts(i)
tempDuration = breakDurations(i)
breakStarts(i) = breakStarts(j)
breakDurations(i) = breakDurations(j)
breakStarts(j) = tempStart
breakDurations(j) = tempDuration
End If
Next j
Next i
' Initialize next break index
Dim nextBreak As Integer
nextBreak = 1
' Clear previous data in Task Tracker sheet (from row 2 down)
wsTracker.Range("A2:H" & wsTracker.Rows.Count).ClearContents
' Initialize random number generator
Randomize
' Start generating tasks
Dim taskRow As Long
taskRow = 2 ' Start from row 2
Do While totalDuration < minTotalDuration And orgCodes.Count > 0
' Select a random Org Code from the collection
Dim selectedOrg As String
Dim randIndex As Integer
randIndex = Int((orgCodes.Count) * Rnd + 1) ' Generate random index between 1 and orgCodes.Count
selectedOrg = orgCodes.Item(randIndex)
' Remove the selected Org Code from the collection to prevent reuse
orgCodes.Remove randIndex
' Select a Function based on weighted probabilities
Dim selectedTaskIndex As Integer
selectedTaskIndex = GetWeightedRandomTaskIndex(taskWeights, numTasks)
Dim selectedTask As String
selectedTask = taskNames(selectedTaskIndex)
' Get corresponding duration range
Dim minDuration As Integer, maxDuration As Integer
minDuration = taskMinDurations(selectedTaskIndex)
maxDuration = taskMaxDurations(selectedTaskIndex)
' Assign a random duration within the range
Dim taskDuration As Integer
taskDuration = Int((maxDuration - minDuration + 1) * Rnd + minDuration)
' Check if adding this duration would exceed maxTotalDuration
If (totalDuration + taskDuration) > maxTotalDuration Then
taskDuration = maxTotalDuration - totalDuration
If taskDuration <= 0 Then Exit Do
End If
' Check if task overlaps with a break
Dim potentialEndTime As Date
potentialEndTime = currentTime + (taskDuration / (24 * 60))
Dim overlap As Boolean
overlap = False
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
overlap = True
Exit For
End If
Next i
If overlap Then
' Advance current time to after the overlapping break
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
currentTime = breakStarts(i) + (breakDurations(i) / (24 * 60))
nextBreak = i + 1
Exit For
End If
Next i
GoTo ContinueLoop
End If
' Get the corresponding Remark for the selected Function
Dim funcRemark As String
funcRemark = GetRemarkForFunction(wsSettings, 4, 5, selectedTask)
' Write to Task Tracker sheet
With wsTracker
.Range("A" & taskRow).Value = Format(startTime, "m/d/yyyy h:mm AM/PM")
.Range("B" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy h:mm AM/PM")
.Range("C" & taskRow).Value = Format(currentTime, "h:mm AM/PM")
.Range("D" & taskRow).Value = Format(potentialEndTime, "h:mm AM/PM")
.Range("E" & taskRow).Value = taskDuration
.Range("F" & taskRow).Value = selectedOrg
.Range("G" & taskRow).Value = selectedTask
.Range("H" & taskRow).Value = funcRemark
End With
' Update variables
currentTime = potentialEndTime
totalDuration = totalDuration + taskDuration
taskRow = taskRow + 1
' VBA Code to Initialize Workbook and Generate Task Tracker
' Place this code in a standard module (Insert > Module) in the VBA editor.
Option Explicit
' Subroutine to initialize the workbook: create sheets, set up columns, add button
Sub InitializeTaskTracker()
Dim wsTaskTracker As Worksheet
Dim wsSettings As Worksheet
Dim shp As Shape
Dim btnLeft As Double, btnTop As Double, btnWidth As Double, btnHeight As Double
Dim btnName As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Attempt to set Task Tracker sheet; if it doesn't exist, create it
On Error Resume Next
Set wsTaskTracker = ThisWorkbook.Worksheets("Task Tracker")
On Error GoTo 0
If wsTaskTracker Is Nothing Then
Set wsTaskTracker = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
wsTaskTracker.Name = "Task Tracker"
Else
' Clear existing content
wsTaskTracker.Cells.Clear
End If
' Attempt to set Settings sheet; if it doesn't exist, create it
On Error Resume Next
Set wsSettings = ThisWorkbook.Worksheets("Settings")
On Error GoTo 0
If wsSettings Is Nothing Then
Set wsSettings = ThisWorkbook.Worksheets.Add(After:=wsTaskTracker)
wsSettings.Name = "Settings"
Else
' Clear existing content
wsSettings.Cells.Clear
End If
' Set up columns in Task Tracker
With wsTaskTracker
.Range("A1").Value = "Date Offered"
.Range("B1").Value = "Date Completed"
.Range("C1").Value = "Time Started"
.Range("D1").Value = "Time Finished"
.Range("E1").Value = "Duration (mins)"
.Range("F1").Value = "Reference Number"
.Range("G1").Value = "Function/Job Classification"
.Range("H1").Value = "Remarks/Notes"
' Format header as bold and apply background color
With .Range("A1:H1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:H").AutoFit
End With
' Set up Settings sheet
With wsSettings
' Define parameters and labels
.Range("A1").Value = "Parameter"
.Range("B1").Value = "Value"
.Range("A2").Value = "Start Time (m/d/yyyy h:mm AM/PM)"
' Example: 10/5/2023 8:00 AM (User should modify as needed)
.Range("B2").Value = "10/5/2023 8:00:00.000 AM"
.Range("A3").Value = "First Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B3").Value = "10/5/2023 10:00 AM"
.Range("A4").Value = "First Break Duration (mins)"
.Range("B4").Value = 13
.Range("A5").Value = "Lunch Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B5").Value = "10/5/2023 12:30 PM"
.Range("A6").Value = "Lunch Break Duration (mins)"
.Range("B6").Value = 55
.Range("A7").Value = "Last Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B7").Value = "10/5/2023 3:30 PM"
.Range("A8").Value = "Last Break Duration (mins)"
.Range("B8").Value = 15
' Headers for Org Codes, Functions, and Remarks
.Range("C9").Value = "Org Codes"
.Range("D9").Value = "Function/Job Classification"
.Range("E9").Value = "Remarks/Notes"
With .Range("C9:E9")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Example Org Codes
.Range("C10").Value = "ORG001"
.Range("C11").Value = "ORG002"
.Range("C12").Value = "ORG003"
' Add more Org Codes as needed
' Example Functions and Remarks
.Range("D10").Value = "Checking Organization Records"
.Range("D11").Value = "Creating Organization Records"
.Range("D12").Value = "Email Management"
.Range("D13").Value = "PowerBi"
.Range("D14").Value = "Updating Organization"
.Range("D15").Value = "Uploading Edocs"
.Range("D16").Value = "Verifying Temporary Accounts"
.Range("D17").Value = "OBPI Adhoc"
.Range("E10").Value = "Remark for Checking Organization Records"
.Range("E11").Value = "Remark for Creating Organization Records"
.Range("E12").Value = "Remark for Email Management"
.Range("E13").Value = "Remark for PowerBi"
.Range("E14").Value = "Remark for Updating Organization"
.Range("E15").Value = "Remark for Uploading Edocs"
.Range("E16").Value = "Remark for Verifying Temporary Accounts"
.Range("E17").Value = "Remark for OBPI Adhoc"
' Add more Remarks as needed
' Format headers for Parameter
With .Range("A1:B1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:E").AutoFit
End With
' Remove existing "Generate Tasks" button if it exists
btnName = "btnGenerateTasks"
On Error Resume Next
wsTaskTracker.Shapes(btnName).Delete
On Error GoTo 0
' Add a button to Task Tracker sheet to run GenerateTasks macro using Shapes.AddFormControl
With wsTaskTracker
' Define button dimensions and position
btnLeft = 10
btnTop = 10
btnWidth = 120
btnHeight = 30
' Add the button as a Form Control
Set shp = .Shapes.AddFormControl(Type:=xlButtonControl, Left:=btnLeft, Top:=btnTop, Width:=btnWidth, Height:=btnHeight)
With shp
.OnAction = "GenerateTasks"
.Name = btnName
.TextFrame.Characters.Text = "Generate Tasks"
.TextFrame.HorizontalAlignment = xlHAlignCenter
.TextFrame.VerticalAlignment = xlVAlignCenter
.Fill.ForeColor.RGB = RGB(0, 112, 192) ' Optional: Button color
.Fill.Transparency = 0
.Line.Visible = msoFalse ' Optional: Remove button border
.TextFrame.Characters.Font.Color = RGB(255, 255, 255) ' Optional: Text color
.TextFrame.Characters.Font.Bold = True
End With
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Workbook initialized successfully! Please configure the 'Settings' sheet before generating tasks.", vbInformation
End Sub
' Subroutine to generate tasks based on Settings
Sub GenerateTasks()
Dim wsTracker As Worksheet
Dim wsSettings As Worksheet
Set wsTracker = ThisWorkbook.Worksheets("Task Tracker")
Set wsSettings = ThisWorkbook.Worksheets("Settings")
' Read Start Time
Dim startTime As Date
If IsDate(wsSettings.Range("B2").Value) Then
startTime = wsSettings.Range("B2").Value
Else
MsgBox "Please enter a valid Start Time in the 'Settings' sheet (cell B2).", vbExclamation
Exit Sub
End If
' Read Break Start Times and Durations
Dim break1Start As Date, break1Duration As Double
Dim lunchBreakStart As Date, lunchBreakDuration As Double
Dim break2Start As Date, break2Duration As Double
If IsDate(wsSettings.Range("B3").Value) Then
break1Start = wsSettings.Range("B3").Value
Else
MsgBox "Please enter a valid First Break Start Time in the 'Settings' sheet (cell B3).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B4").Value) Then
break1Duration = wsSettings.Range("B4").Value
Else
MsgBox "Please enter a valid First Break Duration in minutes in the 'Settings' sheet (cell B4).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B5").Value) Then
lunchBreakStart = wsSettings.Range("B5").Value
Else
MsgBox "Please enter a valid Lunch Break Start Time in the 'Settings' sheet (cell B5).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B6").Value) Then
lunchBreakDuration = wsSettings.Range("B6").Value
Else
MsgBox "Please enter a valid Lunch Break Duration in minutes in the 'Settings' sheet (cell B6).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B7").Value) Then
break2Start = wsSettings.Range("B7").Value
Else
MsgBox "Please enter a valid Last Break Start Time in the 'Settings' sheet (cell B7).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B8").Value) Then
break2Duration = wsSettings.Range("B8").Value
Else
MsgBox "Please enter a valid Last Break Duration in minutes in the 'Settings' sheet (cell B8).", vbExclamation
Exit Sub
End If
' Read Org Codes from Settings, Column C, starting from C10 down
Dim orgCodes As Collection
Set orgCodes = GetOrgCodes(wsSettings, 3, 10) ' Column C, starting from row 10
If orgCodes.Count = 0 Then
MsgBox "Please enter at least one Org Code in the 'Settings' sheet (column C starting from row 10).", vbExclamation
Exit Sub
End If
' Read Functions and Remarks from Settings, Columns D and E, starting from D10 and E10
Dim functionsList As Collection
Dim remarksList As Collection
Set functionsList = GetFunctionsList(wsSettings, 4, 10) ' Column D
Set remarksList = GetRemarksList(wsSettings, 5, 10) ' Column E
If functionsList.Count = 0 Then
MsgBox "Please enter at least one Function/Job Classification in the 'Settings' sheet (column D starting from row 10).", vbExclamation
Exit Sub
End If
If remarksList.Count = 0 Then
MsgBox "Please enter at least one Remark/Notes in the 'Settings' sheet (column E starting from row 10).", vbExclamation
Exit Sub
End If
' Define tasks with their probabilities and duration ranges
' Ensure that the number of tasks matches the entries in Settings
Dim taskNames As Variant
Dim taskWeights As Variant
Dim taskMinDurations As Variant
Dim taskMaxDurations As Variant
Dim numTasks As Integer
' Initialize task arrays
taskNames = Array("Checking Organization Records", "Creating Organization Records", "Email Management", _
"PowerBi", "Updating Organization", "Uploading Edocs", "Verifying Temporary Accounts", "OBPI Adhoc")
taskWeights = Array(80, 10, 80, 40, 30, 60, 80, 10) ' Corresponding to weights
taskMinDurations = Array(1, 10, 2, 2, 5, 1, 1, 10)
taskMaxDurations = Array(3, 12, 3, 3, 6, 2, 2, 20)
numTasks = UBound(taskNames) - LBound(taskNames) + 1
' Validate that task arrays align with Settings entries
If numTasks <> functionsList.Count Or numTasks <> remarksList.Count Then
MsgBox "Mismatch between defined tasks and Settings entries. Please ensure they align.", vbExclamation
Exit Sub
End If
' Define total desired duration in minutes (7 hrs 30 mins to 7 hrs 35 mins)
Dim minTotalDuration As Double, maxTotalDuration As Double
minTotalDuration = 450 ' 7*60 + 30
maxTotalDuration = 455 ' 7*60 + 35
' Initialize variables for task generation
Dim currentTime As Date
currentTime = startTime
Dim totalDuration As Double
totalDuration = 0
' Define Breaks as arrays
Dim breakStarts(1 To 3) As Date
Dim breakDurations(1 To 3) As Double
breakStarts(1) = break1Start
breakDurations(1) = break1Duration
breakStarts(2) = lunchBreakStart
breakDurations(2) = lunchBreakDuration
breakStarts(3) = break2Start
breakDurations(3) = break2Duration
' Sort breaks by start time in ascending order
Dim i As Integer, j As Integer
Dim tempStart As Date, tempDuration As Double
For i = 1 To 2
For j = i + 1 To 3
If breakStarts(i) > breakStarts(j) Then
tempStart = breakStarts(i)
tempDuration = breakDurations(i)
breakStarts(i) = breakStarts(j)
breakDurations(i) = breakDurations(j)
breakStarts(j) = tempStart
breakDurations(j) = tempDuration
End If
Next j
Next i
' Initialize next break index
Dim nextBreak As Integer
nextBreak = 1
' Clear previous data in Task Tracker sheet (from row 2 down)
wsTracker.Range("A2:H" & wsTracker.Rows.Count).ClearContents
' Initialize random number generator
Randomize
' Start generating tasks
Dim taskRow As Long
taskRow = 2 ' Start from row 2
Do While totalDuration < minTotalDuration And orgCodes.Count > 0
' Select a random Org Code from the collection
Dim selectedOrg As String
Dim randIndex As Integer
randIndex = Int((orgCodes.Count) * Rnd + 1) ' Generate random index between 1 and orgCodes.Count
selectedOrg = orgCodes.Item(randIndex)
' Remove the selected Org Code from the collection to prevent reuse
orgCodes.Remove randIndex
' Select a Function based on weighted probabilities
Dim selectedTaskIndex As Integer
selectedTaskIndex = GetWeightedRandomTaskIndex(taskWeights, numTasks)
Dim selectedTask As String
selectedTask = taskNames(selectedTaskIndex)
' Get corresponding duration range
Dim minDuration As Integer, maxDuration As Integer
minDuration = taskMinDurations(selectedTaskIndex)
maxDuration = taskMaxDurations(selectedTaskIndex)
' Assign a random duration within the range
Dim taskDuration As Integer
taskDuration = Int((maxDuration - minDuration + 1) * Rnd + minDuration)
' Check if adding this duration would exceed maxTotalDuration
If (totalDuration + taskDuration) > maxTotalDuration Then
taskDuration = maxTotalDuration - totalDuration
If taskDuration <= 0 Then Exit Do
End If
' Determine random milliseconds for added precision
Dim ms As Double
ms = (Rnd * 1000)
' Check if task overlaps with a break
Dim potentialEndTime As Date
potentialEndTime = currentTime + ((taskDuration * 60) + ms) / (24 * 60 * 60)
Dim overlap As Boolean
overlap = False
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
overlap = True
Exit For
End If
Next i
If overlap Then
' Advance current time to after the overlapping break
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
currentTime = breakStarts(i) + (breakDurations(i) / (24 * 60))
nextBreak = i + 1
Exit For
End If
Next i
GoTo ContinueLoop
End If
' Get the corresponding Remark for the selected Function
Dim funcRemark As String
funcRemark = GetRemarkForFunction(wsSettings, 4, 5, selectedTask)
' Write to Task Tracker sheet
With wsTracker
.Range("A" & taskRow).Value = Format(currentTime, "m/d/yyyy") ' Date Offered
.Range("B" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy") ' Date Completed
.Range("C" & taskRow).Value = Format(currentTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Started
.Range("D" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Finished
.Range("E" & taskRow).Value = taskDuration + Round(ms / 1000, 3) ' Duration in fraction of minutes
.Range("F" & taskRow).Value = selectedOrg
.Range("G" & taskRow).Value = selectedTask
.Range("H" & taskRow).Value = funcRemark
End With
' Update variables
currentTime = potentialEndTime + (Rnd * 3 + 1) / (24 * 60 * 60) ' Add delay of 1 to 3 seconds before next start
totalDuration = totalDuration + taskDuration
taskRow = taskRow + 1
ContinueLoop:
Loop
' Optionally, format the Task Tracker sheet
With wsTracker
.Columns("A:H").AutoFit
' Format columns
.Columns("A").NumberFormat = "m/d/yyyy" ' Date only
.Columns("B").NumberFormat = "m/d/yyyy" ' Date only
.Columns("C").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM" ' Date with time and milliseconds
.Columns("D").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM" ' Date with time and milliseconds
End With
MsgBox "Tasks generated successfully in the 'Task Tracker' sheet.", vbInformation
End Sub
' Function to get Org Codes from a column starting from a specific row
Function GetOrgCodes(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim orgCodes As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
orgCodes.Add ws.Cells(i, col).Value
End If
Next i
Set GetOrgCodes = orgCodes
End Function
' Function to get Functions from a column starting from a specific row
Function GetFunctionsList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim funcList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
funcList.Add ws.Cells(i, col).Value
End If
Next i
Set GetFunctionsList = funcList
End Function
' Function to get Remarks from a column starting from a specific row
Function GetRemarksList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim remarksList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
remarksList.Add ws.Cells(i, col).Value
End If
Next i
Set GetRemarksList = remarksList
End Function
' Function to perform weighted random selection
' probabilities array contains weights
' numTasks is the number of tasks
Function GetWeightedRandomTaskIndex(probabilities As Variant, numTasks As Integer) As Integer
Dim totalWeight As Double
Dim i As Integer
totalWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
totalWeight = totalWeight + probabilities(i)
Next i
Dim randVal As Double
randVal = Rnd * totalWeight
Dim cumulativeWeight As Double
cumulativeWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
cumulativeWeight = cumulativeWeight + probabilities(i)
If randVal <= cumulativeWeight Then
GetWeightedRandomTaskIndex = i
Exit Function
End If
Next i
' In case of rounding errors
GetWeightedRandomTaskIndex = UBound(probabilities)
End Function
' Function to get Remark for a given Function
Function GetRemarkForFunction(ws As Worksheet, funcCol As Integer, remarkCol As Integer, functionName As String) As String
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, funcCol).End(xlUp).Row
Dim i As Long
For i = 10 To lastRow ' Starting from row 10
If Trim(ws.Cells(i, funcCol).Value) = Trim(functionName) Then
GetRemarkForFunction = ws.Cells(i, remarkCol).Value
Exit Function
End If
Next i
' If not found, return empty string
GetRemarkForFunction = ""
End Function
This updated code ensures that:
Date Offered and Date Completed display only the date without time.
Time Started and Time Finished include milliseconds in their format.
The random generation of the "Time Started" for subsequent tasks incorporates a 1-3 seconds delay with milliseconds.
Formulas and number formats have been adjusted accordingly.
Ensure proper testing within the Excel environment, as VBA can behave differently depending on Excel's version and settings.
'[...] Rest of Your Code
' Start generating tasks
Dim taskRow As Long
taskRow = 2 ' Start from row 2
Do While totalDuration < minTotalDuration And orgCodes.Count > 0
' Select a random Org Code from the collection
Dim selectedOrg As String
Dim randIndex As Integer
randIndex = Int((orgCodes.Count) * Rnd + 1) ' Generate random index between 1 and orgCodes.Count
selectedOrg = orgCodes.Item(randIndex)
' Remove the selected Org Code from the collection to prevent reuse
orgCodes.Remove randIndex
' Select a Function based on weighted probabilities
Dim selectedTaskIndex As Integer
selectedTaskIndex = GetWeightedRandomTaskIndex(taskWeights, numTasks)
Dim selectedTask As String
selectedTask = taskNames(selectedTaskIndex)
' Get corresponding duration range
Dim minDuration As Integer, maxDuration As Integer
minDuration = taskMinDurations(selectedTaskIndex)
maxDuration = taskMaxDurations(selectedTaskIndex)
' Assign a random duration within the range
Dim taskDuration As Integer
taskDuration = Int((maxDuration - minDuration + 1) * Rnd + minDuration)
' Check if adding this duration would exceed maxTotalDuration
If (totalDuration + taskDuration) > maxTotalDuration Then
taskDuration = maxTotalDuration - totalDuration
If taskDuration <= 0 Then Exit Do
End If
' Determine random milliseconds for added precision
Dim ms As Long
ms = CLng(Rnd * 1000)
' Calculate potential end time
Dim potentialEndTime As Date
potentialEndTime = DateAdd("s", taskDuration * 60 + ms / 1000, currentTime)
' Check if task overlaps with a break
Dim overlap As Boolean
overlap = False
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
overlap = True
Exit For
End If
Next i
If overlap Then
' Advance current time to after the overlapping break
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
currentTime = breakStarts(i) + (breakDurations(i) / (24 * 60))
nextBreak = i + 1
Exit For
End If
Next i
GoTo ContinueLoop
End If
' Get the corresponding Remark for the selected Function
Dim funcRemark As String
funcRemark = GetRemarkForFunction(wsSettings, 4, 5, selectedTask)
' Write to Task Tracker sheet
With wsTracker
.Range("A" & taskRow).Value = Format(currentTime, "m/d/yyyy") ' Date Offered
.Range("B" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy") ' Date Completed
.Range("C" & taskRow).Value = Format(currentTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Started
.Range("D" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Finished
.Range("E" & taskRow).Value = taskDuration + Round(ms / 1000, 3) ' Duration in fraction of minutes
.Range("F" & taskRow).Value = selectedOrg
.Range("G" & taskRow).Value = selectedTask
.Range("H" & taskRow).Value = funcRemark
End With
' Update variables
currentTime = DateAdd("s", (Rnd * 3 + 1), potentialEndTime) ' Add delay of 1 to 3 seconds before next start
totalDuration = totalDuration + taskDuration
taskRow = taskRow + 1
ContinueLoop:
Loop
'[...] Rest of Your Code
Key Changes:
Utilized DateAdd for adding seconds and fractions thereof for precision on millisecond handling.
Added Dim ms As Long to ensure consistent variable type for milliseconds calculation.
These changes should ensure that your times are processed correctly and avoid direct arithmetic with dates in Excel VBA, which can be problematic with small time increments like milliseconds.
' VBA Code to Initialize Workbook and Generate Task Tracker
' Place this code in a standard module (Insert > Module) in the VBA editor.
Option Explicit
' Subroutine to initialize the workbook: create sheets, set up columns, add button
Sub InitializeTaskTracker()
Dim wsTaskTracker As Worksheet
Dim wsSettings As Worksheet
Dim shp As Shape
Dim btnLeft As Double, btnTop As Double, btnWidth As Double, btnHeight As Double
Dim btnName As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Attempt to set Task Tracker sheet; if it doesn't exist, create it
On Error Resume Next
Set wsTaskTracker = ThisWorkbook.Worksheets("Task Tracker")
On Error GoTo 0
If wsTaskTracker Is Nothing Then
Set wsTaskTracker = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
wsTaskTracker.Name = "Task Tracker"
Else
' Clear existing content
wsTaskTracker.Cells.Clear
End If
' Attempt to set Settings sheet; if it doesn't exist, create it
On Error Resume Next
Set wsSettings = ThisWorkbook.Worksheets("Settings")
On Error GoTo 0
If wsSettings Is Nothing Then
Set wsSettings = ThisWorkbook.Worksheets.Add(After:=wsTaskTracker)
wsSettings.Name = "Settings"
Else
' Clear existing content
wsSettings.Cells.Clear
End If
' Set up columns in Task Tracker
With wsTaskTracker
.Range("A1").Value = "Date Offered"
.Range("B1").Value = "Date Completed"
.Range("C1").Value = "Time Started"
.Range("D1").Value = "Time Finished"
.Range("E1").Value = "Duration (mins)"
.Range("F1").Value = "Reference Number"
.Range("G1").Value = "Function/Job Classification"
.Range("H1").Value = "Remarks/Notes"
' Format header as bold and apply background color
With .Range("A1:H1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:H").AutoFit
End With
' Set up Settings sheet
With wsSettings
' Define parameters and labels
.Range("A1").Value = "Parameter"
.Range("B1").Value = "Value"
.Range("A2").Value = "Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B2").Value = "10/5/2023 8:00:00.000 AM" ' User should modify as needed
.Range("A3").Value = "First Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B3").Value = "10/5/2023 10:00 AM"
.Range("A4").Value = "First Break Duration (mins)"
.Range("B4").Value = 13
.Range("A5").Value = "Lunch Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B5").Value = "10/5/2023 12:30 PM"
.Range("A6").Value = "Lunch Break Duration (mins)"
.Range("B6").Value = 55
.Range("A7").Value = "Last Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B7").Value = "10/5/2023 3:30 PM"
.Range("A8").Value = "Last Break Duration (mins)"
.Range("B8").Value = 15
' Headers for Org Codes, Functions, and Remarks
.Range("C9").Value = "Org Codes"
.Range("D9").Value = "Function/Job Classification"
.Range("E9").Value = "Remarks/Notes"
With .Range("C9:E9")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Example Org Codes
.Range("C10").Value = "ORG001"
.Range("C11").Value = "ORG002"
.Range("C12").Value = "ORG003"
' Add more Org Codes as needed
' Example Functions and Remarks
.Range("D10").Value = "Checking Organization Records"
.Range("D11").Value = "Creating Organization Records"
.Range("D12").Value = "Email Management"
.Range("D13").Value = "PowerBi"
.Range("D14").Value = "Updating Organization"
.Range("D15").Value = "Uploading Edocs"
.Range("D16").Value = "Verifying Temporary Accounts"
.Range("D17").Value = "OBPI Adhoc"
.Range("E10").Value = "Remark for Checking Organization Records"
.Range("E11").Value = "Remark for Creating Organization Records"
.Range("E12").Value = "Remark for Email Management"
.Range("E13").Value = "Remark for PowerBi"
.Range("E14").Value = "Remark for Updating Organization"
.Range("E15").Value = "Remark for Uploading Edocs"
.Range("E16").Value = "Remark for Verifying Temporary Accounts"
.Range("E17").Value = "Remark for OBPI Adhoc"
' Add more Remarks as needed
' Format headers for Parameter
With .Range("A1:B1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:E").AutoFit
End With
' Remove existing "Generate Tasks" button if it exists
btnName = "btnGenerateTasks"
On Error Resume Next
wsTaskTracker.Shapes(btnName).Delete
On Error GoTo 0
' Add a button to Task Tracker sheet to run GenerateTasks macro using Shapes.AddFormControl
With wsTaskTracker
' Define button dimensions and position
btnLeft = 10
btnTop = 10
btnWidth = 120
btnHeight = 30
' Add the button as a Form Control
Set shp = .Shapes.AddFormControl(Type:=xlButtonControl, Left:=btnLeft, Top:=btnTop, Width:=btnWidth, Height:=btnHeight)
With shp
.OnAction = "GenerateTasks"
.Name = btnName
.TextFrame.Characters.Text = "Generate Tasks"
.TextFrame.HorizontalAlignment = xlHAlignCenter
.TextFrame.VerticalAlignment = xlVAlignCenter
.Fill.ForeColor.RGB = RGB(0, 112, 192) ' Optional: Button color
.Fill.Transparency = 0
.Line.Visible = msoFalse ' Optional: Remove button border
.TextFrame.Characters.Font.Color = RGB(255, 255, 255) ' Optional: Text color
.TextFrame.Characters.Font.Bold = True
End With
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Workbook initialized successfully! Please configure the 'Settings' sheet before generating tasks.", vbInformation
End Sub
' Subroutine to generate tasks based on Settings
Sub GenerateTasks()
Dim wsTracker As Worksheet
Dim wsSettings As Worksheet
Set wsTracker = ThisWorkbook.Worksheets("Task Tracker")
Set wsSettings = ThisWorkbook.Worksheets("Settings")
' Read Start Time
Dim startTime As Date
If IsDate(wsSettings.Range("B2").Value) Then
startTime = wsSettings.Range("B2").Value
Else
MsgBox "Please enter a valid Start Time in the 'Settings' sheet (cell B2).", vbExclamation
Exit Sub
End If
' Read Break Start Times and Durations
Dim break1Start As Date, break1Duration As Double
Dim lunchBreakStart As Date, lunchBreakDuration As Double
Dim break2Start As Date, break2Duration As Double
If IsDate(wsSettings.Range("B3").Value) Then
break1Start = wsSettings.Range("B3").Value
Else
MsgBox "Please enter a valid First Break Start Time in the 'Settings' sheet (cell B3).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B4").Value) Then
break1Duration = wsSettings.Range("B4").Value
Else
MsgBox "Please enter a valid First Break Duration in minutes in the 'Settings' sheet (cell B4).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B5").Value) Then
lunchBreakStart = wsSettings.Range("B5").Value
Else
MsgBox "Please enter a valid Lunch Break Start Time in the 'Settings' sheet (cell B5).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B6").Value) Then
lunchBreakDuration = wsSettings.Range("B6").Value
Else
MsgBox "Please enter a valid Lunch Break Duration in minutes in the 'Settings' sheet (cell B6).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B7").Value) Then
break2Start = wsSettings.Range("B7").Value
Else
MsgBox "Please enter a valid Last Break Start Time in the 'Settings' sheet (cell B7).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B8").Value) Then
break2Duration = wsSettings.Range("B8").Value
Else
MsgBox "Please enter a valid Last Break Duration in minutes in the 'Settings' sheet (cell B8).", vbExclamation
Exit Sub
End If
' Read Org Codes from Settings, Column C, starting from C10 down
Dim orgCodes As Collection
Set orgCodes = GetOrgCodes(wsSettings, 3, 10) ' Column C, starting from row 10
If orgCodes.Count = 0 Then
MsgBox "Please enter at least one Org Code in the 'Settings' sheet (column C starting from row 10).", vbExclamation
Exit Sub
End If
' Read Functions and Remarks from Settings, Columns D and E, starting from D10 and E10
Dim functionsList As Collection
Dim remarksList As Collection
Set functionsList = GetFunctionsList(wsSettings, 4, 10) ' Column D
Set remarksList = GetRemarksList(wsSettings, 5, 10) ' Column E
If functionsList.Count = 0 Then
MsgBox "Please enter at least one Function/Job Classification in the 'Settings' sheet (column D starting from row 10).", vbExclamation
Exit Sub
End If
If remarksList.Count = 0 Then
MsgBox "Please enter at least one Remark/Notes in the 'Settings' sheet (column E starting from row 10).", vbExclamation
Exit Sub
End If
' Define tasks with their probabilities and duration ranges
' Ensure that the number of tasks matches the entries in Settings
Dim taskNames As Variant
Dim taskWeights As Variant
Dim taskMinDurations As Variant
Dim taskMaxDurations As Variant
Dim numTasks As Integer
' Initialize task arrays
taskNames = Array("Checking Organization Records", "Creating Organization Records", "Email Management", _
"PowerBi", "Updating Organization", "Uploading Edocs", "Verifying Temporary Accounts", "OBPI Adhoc")
taskWeights = Array(80, 10, 80, 40, 30, 60, 80, 10) ' Corresponding to weights
taskMinDurations = Array(1, 10, 2, 2, 5, 1, 1, 10)
taskMaxDurations = Array(3, 12, 3, 3, 6, 2, 2, 20)
numTasks = UBound(taskNames) - LBound(taskNames) + 1
' Validate that task arrays align with Settings entries
If numTasks <> functionsList.Count Or numTasks <> remarksList.Count Then
MsgBox "Mismatch between defined tasks and Settings entries. Please ensure they align.", vbExclamation
Exit Sub
End If
' Define total desired duration in minutes (7 hrs 30 mins to 7 hrs 35 mins)
Dim minTotalDuration As Double, maxTotalDuration As Double
minTotalDuration = 450 ' 7*60 + 30
maxTotalDuration = 455 ' 7*60 + 35
' Initialize variables for task generation
Dim currentTime As Date
currentTime = startTime
Dim totalDuration As Double
totalDuration = 0
' Define Breaks as arrays
Dim breakStarts(1 To 3) As Date
Dim breakDurations(1 To 3) As Double
breakStarts(1) = break1Start
breakDurations(1) = break1Duration
breakStarts(2) = lunchBreakStart
breakDurations(2) = lunchBreakDuration
breakStarts(3) = break2Start
breakDurations(3) = break2Duration
' Sort breaks by start time in ascending order
Dim i As Integer, j As Integer
Dim tempStart As Date, tempDuration As Double
For i = 1 To 2
For j = i + 1 To 3
If breakStarts(i) > breakStarts(j) Then
tempStart = breakStarts(i)
tempDuration = breakDurations(i)
breakStarts(i) = breakStarts(j)
breakDurations(i) = breakDurations(j)
breakStarts(j) = tempStart
breakDurations(j) = tempDuration
End If
Next j
Next i
' Initialize next break index
Dim nextBreak As Integer
nextBreak = 1
' Clear previous data in Task Tracker sheet (from row 2 down)
wsTracker.Range("A2:H" & wsTracker.Rows.Count).ClearContents
' Initialize random number generator
Randomize
' Start generating tasks
Dim taskRow As Long
taskRow = 2 ' Start from row 2
Do While totalDuration < minTotalDuration And orgCodes.Count > 0
' Select a random Org Code from the collection
Dim selectedOrg As String
Dim randIndex As Integer
randIndex = Int((orgCodes.Count) * Rnd + 1) ' Generate random index between 1 and orgCodes.Count
selectedOrg = orgCodes.Item(randIndex)
' Remove the selected Org Code from the collection to prevent reuse
orgCodes.Remove randIndex
' Select a Function based on weighted probabilities
Dim selectedTaskIndex As Integer
selectedTaskIndex = GetWeightedRandomTaskIndex(taskWeights, numTasks)
Dim selectedTask As String
selectedTask = taskNames(selectedTaskIndex)
' Get corresponding duration range
Dim minDuration As Integer, maxDuration As Integer
minDuration = taskMinDurations(selectedTaskIndex)
maxDuration = taskMaxDurations(selectedTaskIndex)
' Assign a random duration within the range
Dim taskDuration As Integer
taskDuration = Int((maxDuration - minDuration + 1) * Rnd + minDuration)
' Check if adding this duration would exceed maxTotalDuration
If (totalDuration + taskDuration) > maxTotalDuration Then
taskDuration = maxTotalDuration - totalDuration
If taskDuration <= 0 Then Exit Do
End If
' Determine random milliseconds for added precision
Dim ms As Long
ms = CLng(Rnd * 1000)
' Calculate potential end time
Dim potentialEndTime As Date
potentialEndTime = DateAdd("s", taskDuration * 60 + ms / 1000, currentTime)
' Check if task overlaps with a break
Dim overlap As Boolean
overlap = False
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
overlap = True
Exit For
End If
Next i
If overlap Then
' Advance current time to after the overlapping break
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
currentTime = breakStarts(i) + (breakDurations(i) / (24 * 60))
nextBreak = i + 1
Exit For
End If
Next i
GoTo ContinueLoop
End If
' Get the corresponding Remark for the selected Function
Dim funcRemark As String
funcRemark = GetRemarkForFunction(wsSettings, 4, 5, selectedTask)
' Write to Task Tracker sheet
With wsTracker
.Range("A" & taskRow).Value = Format(currentTime, "m/d/yyyy") ' Date Offered
.Range("B" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy") ' Date Completed
.Range("C" & taskRow).Value = Format(currentTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Started
.Range("D" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Finished
.Range("E" & taskRow).Value = taskDuration + Round(ms / 1000, 3) ' Duration in fraction of minutes
.Range("F" & taskRow).Value = selectedOrg
.Range("G" & taskRow).Value = selectedTask
.Range("H" & taskRow).Value = funcRemark
End With
' Update variables
currentTime = DateAdd("s", (Rnd * 3 + 1), potentialEndTime) ' Add delay of 1 to 3 seconds before next start
totalDuration = totalDuration + taskDuration
taskRow = taskRow + 1
ContinueLoop:
Loop
' Optionally, format the Task Tracker sheet
With wsTracker
.Columns("A:H").AutoFit
' Format columns
.Columns("A").NumberFormat = "m/d/yyyy" ' Date only
.Columns("B").NumberFormat = "m/d/yyyy" ' Date only
.Columns("C").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM" ' Date with time and milliseconds
.Columns("D").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM" ' Date with time and milliseconds
End With
MsgBox "Tasks generated successfully in the 'Task Tracker' sheet.", vbInformation
End Sub
' Function to get Org Codes from a column starting from a specific row
Function GetOrgCodes(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim orgCodes As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
orgCodes.Add ws.Cells(i, col).Value
End If
Next i
Set GetOrgCodes = orgCodes
End Function
' Function to get Functions from a column starting from a specific row
Function GetFunctionsList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim funcList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
funcList.Add ws.Cells(i, col).Value
End If
Next i
Set GetFunctionsList = funcList
End Function
' Function to get Remarks from a column starting from a specific row
Function GetRemarksList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim remarksList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
remarksList.Add ws.Cells(i, col).Value
End If
Next i
Set GetRemarksList = remarksList
End Function
' Function to perform weighted random selection
' probabilities array contains weights
' numTasks is the number of tasks
Function GetWeightedRandomTaskIndex(probabilities As Variant, numTasks As Integer) As Integer
Dim totalWeight As Double
Dim i As Integer
totalWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
totalWeight = totalWeight + probabilities(i)
Next i
Dim randVal As Double
randVal = Rnd * totalWeight
Dim cumulativeWeight As Double
cumulativeWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
cumulativeWeight = cumulativeWeight + probabilities(i)
If randVal <= cumulativeWeight Then
GetWeightedRandomTaskIndex = i
Exit Function
End If
Next i
' In case of rounding errors
GetWeightedRandomTaskIndex = UBound(probabilities)
End Function
' Function to get Remark for a given Function
Function GetRemarkForFunction(ws As Worksheet, funcCol As Integer, remarkCol As Integer, functionName As String) As String
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, funcCol).End(xlUp).Row
Dim i As Long
For i = 10 To lastRow ' Starting from row 10
If Trim(ws.Cells(i, funcCol).Value) = Trim(functionName) Then
GetRemarkForFunction = ws.Cells(i, remarkCol).Value
Exit Function
End If
Next i
' If not found, return empty string
GetRemarkForFunction = ""
End Function
Key Modifications:
Date Formatting: Date fields for Date Offered and Date Completed now display only the date (m/d/yyyy format).
Time Formatting: Time fields for Time Started and Time Finished include milliseconds using h:mm:ss.000 AM/PM format.
Milliseconds Calculations: Utilizes DateAdd for adding task duration and random milliseconds to ensure correct time arithmetic and logical continuity in time operations.
Random Start Delay: Uses DateAdd to incorporate a 1–3 seconds randomized delay between tasks including milliseconds for precision.
Ensure to test this code in the VBA editor within Excel to verify correct behavior specific to your version and setup.
' VBA Code to Initialize Workbook and Generate Task Tracker
' Place this code in a standard module (Insert > Module) in the VBA editor.
Option Explicit
' Subroutine to initialize the workbook: create sheets, set up columns, add button
Sub InitializeTaskTracker()
Dim wsTaskTracker As Worksheet
Dim wsSettings As Worksheet
Dim shp As Shape
Dim btnLeft As Double, btnTop As Double, btnWidth As Double, btnHeight As Double
Dim btnName As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Attempt to set Task Tracker sheet; if it doesn't exist, create it
On Error Resume Next
Set wsTaskTracker = ThisWorkbook.Worksheets("Task Tracker")
On Error GoTo 0
If wsTaskTracker Is Nothing Then
Set wsTaskTracker = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
wsTaskTracker.Name = "Task Tracker"
Else
' Clear existing content
wsTaskTracker.Cells.Clear
End If
' Attempt to set Settings sheet; if it doesn't exist, create it
On Error Resume Next
Set wsSettings = ThisWorkbook.Worksheets("Settings")
On Error GoTo 0
If wsSettings Is Nothing Then
Set wsSettings = ThisWorkbook.Worksheets.Add(After:=wsTaskTracker)
wsSettings.Name = "Settings"
Else
' Clear existing content
wsSettings.Cells.Clear
End If
' Set up columns in Task Tracker
With wsTaskTracker
.Range("A1").Value = "Date Offered"
.Range("B1").Value = "Date Completed"
.Range("C1").Value = "Time Started"
.Range("D1").Value = "Time Finished"
.Range("E1").Value = "Duration (h:mm:ss AM/PM)"
.Range("F1").Value = "Reference Number"
.Range("G1").Value = "Function/Job Classification"
.Range("H1").Value = "Remarks/Notes"
' Format header as bold and apply background color
With .Range("A1:H1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:H").AutoFit
End With
' Set up Settings sheet
With wsSettings
' Define parameters and labels
.Range("A1").Value = "Parameter"
.Range("B1").Value = "Value"
.Range("A2").Value = "Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B2").Value = "10/5/2023 8:00:00.000 AM" ' User should modify as needed
.Range("A3").Value = "First Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B3").Value = "10/5/2023 10:00 AM"
.Range("A4").Value = "First Break Duration (mins)"
.Range("B4").Value = 13
.Range("A5").Value = "Lunch Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B5").Value = "10/5/2023 12:30 PM"
.Range("A6").Value = "Lunch Break Duration (mins)"
.Range("B6").Value = 55
.Range("A7").Value = "Last Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B7").Value = "10/5/2023 3:30 PM"
.Range("A8").Value = "Last Break Duration (mins)"
.Range("B8").Value = 15
' Headers for Org Codes, Functions, and Remarks
.Range("C9").Value = "Org Codes"
.Range("D9").Value = "Function/Job Classification"
.Range("E9").Value = "Remarks/Notes"
With .Range("C9:E9")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Example Org Codes
.Range("C10").Value = "ORG001"
.Range("C11").Value = "ORG002"
.Range("C12").Value = "ORG003"
' Add more Org Codes as needed
' Example Functions and Remarks
.Range("D10").Value = "Checking Organization Records"
.Range("D11").Value = "Creating Organization Records"
.Range("D12").Value = "Email Management"
.Range("D13").Value = "PowerBi"
.Range("D14").Value = "Updating Organization"
.Range("D15").Value = "Uploading Edocs"
.Range("D16").Value = "Verifying Temporary Accounts"
.Range("D17").Value = "OBPI Adhoc"
.Range("E10").Value = "Remark for Checking Organization Records"
.Range("E11").Value = "Remark for Creating Organization Records"
.Range("E12").Value = "Remark for Email Management"
.Range("E13").Value = "Remark for PowerBi"
.Range("E14").Value = "Remark for Updating Organization"
.Range("E15").Value = "Remark for Uploading Edocs"
.Range("E16").Value = "Remark for Verifying Temporary Accounts"
.Range("E17").Value = "Remark for OBPI Adhoc"
' Add more Remarks as needed
' Format headers for Parameter
With .Range("A1:B1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:E").AutoFit
End With
' Remove existing "Generate Tasks" button if it exists
btnName = "btnGenerateTasks"
On Error Resume Next
wsTaskTracker.Shapes(btnName).Delete
On Error GoTo 0
' Add a button to Task Tracker sheet to run GenerateTasks macro using Shapes.AddFormControl
With wsTaskTracker
' Define button dimensions and position
btnLeft = 10
btnTop = 10
btnWidth = 120
btnHeight = 30
' Add the button as a Form Control
Set shp = .Shapes.AddFormControl(Type:=xlButtonControl, Left:=btnLeft, Top:=btnTop, Width:=btnWidth, Height:=btnHeight)
With shp
.OnAction = "GenerateTasks"
.Name = btnName
.TextFrame.Characters.Text = "Generate Tasks"
.TextFrame.HorizontalAlignment = xlHAlignCenter
.TextFrame.VerticalAlignment = xlVAlignCenter
.Fill.ForeColor.RGB = RGB(0, 112, 192) ' Optional: Button color
.Fill.Transparency = 0
.Line.Visible = msoFalse ' Optional: Remove button border
.TextFrame.Characters.Font.Color = RGB(255, 255, 255) ' Optional: Text color
.TextFrame.Characters.Font.Bold = True
End With
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Workbook initialized successfully! Please configure the 'Settings' sheet before generating tasks.", vbInformation
End Sub
' Subroutine to generate tasks based on Settings
Sub GenerateTasks()
Dim wsTracker As Worksheet
Dim wsSettings As Worksheet
Set wsTracker = ThisWorkbook.Worksheets("Task Tracker")
Set wsSettings = ThisWorkbook.Worksheets("Settings")
' Read Start Time
Dim startTime As Date
If IsDate(wsSettings.Range("B2").Value) Then
startTime = wsSettings.Range("B2").Value
Else
MsgBox "Please enter a valid Start Time in the 'Settings' sheet (cell B2).", vbExclamation
Exit Sub
End If
' Read Break Start Times and Durations
Dim break1Start As Date, break1Duration As Double
Dim lunchBreakStart As Date, lunchBreakDuration As Double
Dim break2Start As Date, break2Duration As Double
If IsDate(wsSettings.Range("B3").Value) Then
break1Start = wsSettings.Range("B3").Value
Else
MsgBox "Please enter a valid First Break Start Time in the 'Settings' sheet (cell B3).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B4").Value) Then
break1Duration = wsSettings.Range("B4").Value
Else
MsgBox "Please enter a valid First Break Duration in minutes in the 'Settings' sheet (cell B4).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B5").Value) Then
lunchBreakStart = wsSettings.Range("B5").Value
Else
MsgBox "Please enter a valid Lunch Break Start Time in the 'Settings' sheet (cell B5).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B6").Value) Then
lunchBreakDuration = wsSettings.Range("B6").Value
Else
MsgBox "Please enter a valid Lunch Break Duration in minutes in the 'Settings' sheet (cell B6).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B7").Value) Then
break2Start = wsSettings.Range("B7").Value
Else
MsgBox "Please enter a valid Last Break Start Time in the 'Settings' sheet (cell B7).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B8").Value) Then
break2Duration = wsSettings.Range("B8").Value
Else
MsgBox "Please enter a valid Last Break Duration in minutes in the 'Settings' sheet (cell B8).", vbExclamation
Exit Sub
End If
' Read Org Codes from Settings, Column C, starting from C10 down
Dim orgCodes As Collection
Set orgCodes = GetOrgCodes(wsSettings, 3, 10) ' Column C, starting from row 10
If orgCodes.Count = 0 Then
MsgBox "Please enter at least one Org Code in the 'Settings' sheet (column C starting from row 10).", vbExclamation
Exit Sub
End If
' Read Functions and Remarks from Settings, Columns D and E, starting from D10 and E10
Dim functionsList As Collection
Dim remarksList As Collection
Set functionsList = GetFunctionsList(wsSettings, 4, 10) ' Column D
Set remarksList = GetRemarksList(wsSettings, 5, 10) ' Column E
If functionsList.Count = 0 Then
MsgBox "Please enter at least one Function/Job Classification in the 'Settings' sheet (column D starting from row 10).", vbExclamation
Exit Sub
End If
If remarksList.Count = 0 Then
MsgBox "Please enter at least one Remark/Notes in the 'Settings' sheet (column E starting from row 10).", vbExclamation
Exit Sub
End If
' Define tasks with their probabilities and duration ranges
' Ensure that the number of tasks matches the entries in Settings
Dim taskNames As Variant
Dim taskWeights As Variant
Dim taskMinDurations As Variant
Dim taskMaxDurations As Variant
Dim numTasks As Integer
' Initialize task arrays
taskNames = Array("Checking Organization Records", "Creating Organization Records", "Email Management", _
"PowerBi", "Updating Organization", "Uploading Edocs", "Verifying Temporary Accounts", "OBPI Adhoc")
taskWeights = Array(80, 10, 80, 40, 30, 60, 80, 10) ' Corresponding to weights
taskMinDurations = Array(1, 10, 2, 2, 5, 1, 1, 10)
taskMaxDurations = Array(3, 12, 3, 3, 6, 2, 2, 20)
numTasks = UBound(taskNames) - LBound(taskNames) + 1
' Validate that task arrays align with Settings entries
If numTasks <> functionsList.Count Or numTasks <> remarksList.Count Then
MsgBox "Mismatch between defined tasks and Settings entries. Please ensure they align.", vbExclamation
Exit Sub
End If
' Define total desired duration in minutes (7 hrs 30 mins to 7 hrs 35 mins)
Dim minTotalDuration As Double, maxTotalDuration As Double
minTotalDuration = 450 ' 7*60 + 30
maxTotalDuration = 455 ' 7*60 + 35
' Initialize variables for task generation
Dim currentTime As Date
currentTime = startTime
Dim totalDuration As Double
totalDuration = 0
' Define Breaks as arrays
Dim breakStarts(1 To 3) As Date
Dim breakDurations(1 To 3) As Double
breakStarts(1) = break1Start
breakDurations(1) = break1Duration
breakStarts(2) = lunchBreakStart
breakDurations(2) = lunchBreakDuration
breakStarts(3) = break2Start
breakDurations(3) = break2Duration
' Sort breaks by start time in ascending order
Dim i As Integer, j As Integer
Dim tempStart As Date, tempDuration As Double
For i = 1 To 2
For j = i + 1 To 3
If breakStarts(i) > breakStarts(j) Then
tempStart = breakStarts(i)
tempDuration = breakDurations(i)
breakStarts(i) = breakStarts(j)
breakDurations(i) = breakDurations(j)
breakStarts(j) = tempStart
breakDurations(j) = tempDuration
End If
Next j
Next i
' Initialize next break index
Dim nextBreak As Integer
nextBreak = 1
' Clear previous data in Task Tracker sheet (from row 2 down)
wsTracker.Range("A2:H" & wsTracker.Rows.Count).ClearContents
' Initialize random number generator
Randomize
' Start generating tasks
Dim taskRow As Long
taskRow = 2 ' Start from row 2
Do While totalDuration < minTotalDuration And orgCodes.Count > 0
' Select a random Org Code from the collection
Dim selectedOrg As String
Dim randIndex As Integer
randIndex = Int((orgCodes.Count) * Rnd + 1) ' Generate random index between 1 and orgCodes.Count
selectedOrg = orgCodes.Item(randIndex)
' Remove the selected Org Code from the collection to prevent reuse
orgCodes.Remove randIndex
' Select a Function based on weighted probabilities
Dim selectedTaskIndex As Integer
selectedTaskIndex = GetWeightedRandomTaskIndex(taskWeights, numTasks)
Dim selectedTask As String
selectedTask = taskNames(selectedTaskIndex)
' Get corresponding duration range
Dim minDuration As Integer, maxDuration As Integer
minDuration = taskMinDurations(selectedTaskIndex)
maxDuration = taskMaxDurations(selectedTaskIndex)
' Assign a random duration within the range
Dim taskDuration As Integer
taskDuration = Int((maxDuration - minDuration + 1) * Rnd + minDuration)
' Check if adding this duration would exceed maxTotalDuration
If (totalDuration + taskDuration) > maxTotalDuration Then
taskDuration = maxTotalDuration - totalDuration
If taskDuration <= 0 Then Exit Do
End If
' Determine random milliseconds for added precision
Dim ms As Long
ms = CLng(Rnd * 1000)
' Calculate potential end time
Dim potentialEndTime As Date
potentialEndTime = DateAdd("s", taskDuration * 60 + ms / 1000, currentTime)
' Ensure the duration is correctly reflected
taskDuration = DateDiff("s", currentTime, potentialEndTime)
' Check if task overlaps with a break
Dim overlap As Boolean
overlap = False
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
overlap = True
Exit For
End If
Next i
If overlap Then
' Advance current time to after the overlapping break
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
currentTime = breakStarts(i) + (breakDurations(i) / (24 * 60))
nextBreak = i + 1
Exit For
End If
Next i
GoTo ContinueLoop
End If
' Convert duration to Time format
Dim durationTime As String
durationTime = Format(TimeSerial(0, 0, taskDuration) + (ms / 86400 / 1000), "h:mm:ss AM/PM")
' Get the corresponding Remark for the selected Function
Dim funcRemark As String
funcRemark = GetRemarkForFunction(wsSettings, 4, 5, selectedTask)
' Write to Task Tracker sheet
With wsTracker
.Range("A" & taskRow).Value = Format(currentTime, "m/d/yyyy") ' Date Offered
.Range("B" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy") ' Date Completed
.Range("C" & taskRow).Value = Format(currentTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Started
.Range("D" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Finished
.Range("E" & taskRow).Value = durationTime ' Duration formatted
.Range("F" & taskRow).Value = selectedOrg
.Range("G" & taskRow).Value = selectedTask
.Range("H" & taskRow).Value = funcRemark
End With
' Update variables
currentTime = DateAdd("s", (Rnd * 3 + 1), potentialEndTime) ' Add delay of 1 to 3 seconds before next start
totalDuration = totalDuration + taskDuration / 60
taskRow = taskRow + 1
ContinueLoop:
Loop
' Optionally, format the Task Tracker sheet
With wsTracker
.Columns("A:H").AutoFit
' Format columns
.Columns("A").NumberFormat = "m/d/yyyy" ' Date only
.Columns("B").NumberFormat = "m/d/yyyy" ' Date only
.Columns("C").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM" ' Date with time and milliseconds
.Columns("D").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM" ' Date with time and milliseconds
End With
MsgBox "Tasks generated successfully in the 'Task Tracker' sheet.", vbInformation
End Sub
' Function to get Org Codes from a column starting from a specific row
Function GetOrgCodes(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim orgCodes As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
orgCodes.Add ws.Cells(i, col).Value
End If
Next i
Set GetOrgCodes = orgCodes
End Function
' Function to get Functions from a column starting from a specific row
Function GetFunctionsList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim funcList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
funcList.Add ws.Cells(i, col).Value
End If
Next i
Set GetFunctionsList = funcList
End Function
' Function to get Remarks from a column starting from a specific row
Function GetRemarksList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim remarksList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
remarksList.Add ws.Cells(i, col).Value
End If
Next i
Set GetRemarksList = remarksList
End Function
' Function to perform weighted random selection
' probabilities array contains weights
' numTasks is the number of tasks
Function GetWeightedRandomTaskIndex(probabilities As Variant, numTasks As Integer) As Integer
Dim totalWeight As Double
Dim i As Integer
totalWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
totalWeight = totalWeight + probabilities(i)
Next i
Dim randVal As Double
randVal = Rnd * totalWeight
Dim cumulativeWeight As Double
cumulativeWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
cumulativeWeight = cumulativeWeight + probabilities(i)
If randVal <= cumulativeWeight Then
GetWeightedRandomTaskIndex = i
Exit Function
End If
Next i
' In case of rounding errors
GetWeightedRandomTaskIndex = UBound(probabilities)
End Function
' Function to get Remark for a given Function
Function GetRemarkForFunction(ws As Worksheet, funcCol As Integer, remarkCol As Integer, functionName As String) As String
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, funcCol).End(xlUp).Row
Dim i As Long
For i = 10 To lastRow ' Starting from row 10
If Trim(ws.Cells(i, funcCol).Value) = Trim(functionName) Then
GetRemarkForFunction = ws.Cells(i, remarkCol).Value
Exit Function
End If
Next i
' If not found, return empty string
GetRemarkForFunction = ""
End Function
Key Changes:
Duration Calculation: The duration is explicitly calculated using DateDiff and formatted to show in "h:mm:ss AM/PM" format.
Milliseconds: Adjustments ensure that milliseconds are correctly factored into the potential end time calculation.
Duration Formatting: Duration now reflects the actual elapsed time between Time Started and Time Finished with the correct format.
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Attempt to set Task Tracker sheet; if it doesn't exist, create it
On Error Resume Next
Set wsTaskTracker = ThisWorkbook.Worksheets("Task Tracker")
On Error GoTo 0
If wsTaskTracker Is Nothing Then
Set wsTaskTracker = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
wsTaskTracker.Name = "Task Tracker"
Else
' Clear existing content
wsTaskTracker.Cells.Clear
End If
' Attempt to set Settings sheet; if it doesn't exist, create it
On Error Resume Next
Set wsSettings = ThisWorkbook.Worksheets("Settings")
On Error GoTo 0
If wsSettings Is Nothing Then
Set wsSettings = ThisWorkbook.Worksheets.Add(After:=wsTaskTracker)
wsSettings.Name = "Settings"
Else
' Clear existing content
wsSettings.Cells.Clear
End If
' Set up columns in Task Tracker
With wsTaskTracker
.Range("A1").Value = "Date Offered"
.Range("B1").Value = "Date Completed"
.Range("C1").Value = "Time Started"
.Range("D1").Value = "Time Finished"
.Range("E1").Value = "Duration (mins)"
.Range("F1").Value = "Reference Number"
.Range("G1").Value = "Function/Job Classification"
.Range("H1").Value = "Remarks/Notes"
' Format header as bold and apply background color
With .Range("A1:H1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:H").AutoFit
End With
' Set up Settings sheet
With wsSettings
' Define parameters and labels
.Range("A1").Value = "Parameter"
.Range("B1").Value = "Value"
.Range("A2").Value = "Start Time (m/d/yyyy h:mm AM/PM)"
' Example: 10/5/2023 8:00 AM (User should modify as needed)
.Range("B2").Value = "10/5/2023 8:00 AM"
.Range("A3").Value = "First Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B3").Value = "10/5/2023 10:00 AM"
.Range("A4").Value = "First Break Duration (mins)"
.Range("B4").Value = 13
.Range("A5").Value = "Lunch Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B5").Value = "10/5/2023 12:30 PM"
.Range("A6").Value = "Lunch Break Duration (mins)"
.Range("B6").Value = 55
.Range("A7").Value = "Last Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B7").Value = "10/5/2023 3:30 PM"
.Range("A8").Value = "Last Break Duration (mins)"
.Range("B8").Value = 15
' Headers for Org Codes, Functions, and Remarks
.Range("C9").Value = "Org Codes"
.Range("D9").Value = "Function/Job Classification"
.Range("E9").Value = "Remarks/Notes"
With .Range("C9:E9")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Example Org Codes
.Range("C10").Value = "ORG001"
.Range("C11").Value = "ORG002"
.Range("C12").Value = "ORG003"
' Add more Org Codes as needed
' Example Functions and Remarks
.Range("D10").Value = "Checking Organization Records"
.Range("D11").Value = "Creating Organization Records"
.Range("D12").Value = "Email Management"
.Range("D13").Value = "PowerBi"
.Range("D14").Value = "Updating Organization"
.Range("D15").Value = "Uploading Edocs"
.Range("D16").Value = "Verifying Temporary Accounts"
.Range("D17").Value = "OBPI Adhoc"
.Range("E10").Value = "Remark for Checking Organization Records"
.Range("E11").Value = "Remark for Creating Organization Records"
.Range("E12").Value = "Remark for Email Management"
.Range("E13").Value = "Remark for PowerBi"
.Range("E14").Value = "Remark for Updating Organization"
.Range("E15").Value = "Remark for Uploading Edocs"
.Range("E16").Value = "Remark for Verifying Temporary Accounts"
.Range("E17").Value = "Remark for OBPI Adhoc"
' Add more Remarks as needed
' Format headers for Parameter
With .Range("A1:B1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:E").AutoFit
End With
' Remove existing "Generate Tasks" button if it exists
btnName = "btnGenerateTasks"
On Error Resume Next
wsTaskTracker.Shapes(btnName).Delete
On Error GoTo 0
' Add a button to Task Tracker sheet to run GenerateTasks macro using Shapes.AddFormControl
With wsTaskTracker
' Define button dimensions and position
btnLeft = 10
btnTop = 10
btnWidth = 120
btnHeight = 30
' Add the button as a Form Control
Set shp = .Shapes.AddFormControl(Type:=xlButtonControl, Left:=btnLeft, Top:=btnTop, Width:=btnWidth, Height:=btnHeight)
With shp
.OnAction = "GenerateTasks"
.Name = btnName
.TextFrame.Characters.Text = "Generate Tasks"
.TextFrame.HorizontalAlignment = xlHAlignCenter
.TextFrame.VerticalAlignment = xlVAlignCenter
.Fill.ForeColor.RGB = RGB(0, 112, 192) ' Optional: Button color
.Fill.Transparency = 0
.Line.Visible = msoFalse ' Optional: Remove button border
.TextFrame.Characters.Font.Color = RGB(255, 255, 255) ' Optional: Text color
.TextFrame.Characters.Font.Bold = True
End With
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Workbook initialized successfully! Please configure the 'Settings' sheet before generating tasks.", vbInformation
End Sub
' Subroutine to generate tasks based on Settings
Sub GenerateTasks()
Dim wsTracker As Worksheet
Dim wsSettings As Worksheet
code
Set wsTracker = ThisWorkbook.Worksheets("Task Tracker")
Set wsSettings = ThisWorkbook.Worksheets("Settings")
' Read Start Time
Dim startTime As Date
If IsDate(wsSettings.Range("B2").Value) Then
startTime = wsSettings.Range("B2").Value
Else
MsgBox "Please enter a valid Start Time in the 'Settings' sheet (cell B2).", vbExclamation
Exit Sub
End If
' Read Break Start Times and Durations
Dim break1Start As Date, break1Duration As Double
Dim lunchBreakStart As Date, lunchBreakDuration As Double
Dim break2Start As Date, break2Duration As Double
If IsDate(wsSettings.Range("B3").Value) Then
break1Start = wsSettings.Range("B3").Value
Else
MsgBox "Please enter a valid First Break Start Time in the 'Settings' sheet (cell B3).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B4").Value) Then
break1Duration = wsSettings.Range("B4").Value
Else
MsgBox "Please enter a valid First Break Duration in minutes in the 'Settings' sheet (cell B4).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B5").Value) Then
lunchBreakStart = wsSettings.Range("B5").Value
Else
MsgBox "Please enter a valid Lunch Break Start Time in the 'Settings' sheet (cell B5).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B6").Value) Then
lunchBreakDuration = wsSettings.Range("B6").Value
Else
MsgBox "Please enter a valid Lunch Break Duration in minutes in the 'Settings' sheet (cell B6).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B7").Value) Then
break2Start = wsSettings.Range("B7").Value
Else
MsgBox "Please enter a valid Last Break Start Time in the 'Settings' sheet (cell B7).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B8").Value) Then
break2Duration = wsSettings.Range("B8").Value
Else
MsgBox "Please enter a valid Last Break Duration in minutes in the 'Settings' sheet (cell B8).", vbExclamation
Exit Sub
End If
' Read Org Codes from Settings, Column C, starting from C10 down
Dim orgCodes As Collection
Set orgCodes = GetOrgCodes(wsSettings, 3, 10) ' Column C, starting from row 10
If orgCodes.Count = 0 Then
MsgBox "Please enter at least one Org Code in the 'Settings' sheet (column C starting from row 10).", vbExclamation
Exit Sub
End If
' Read Functions and Remarks from Settings, Columns D and E, starting from D10 and E10
Dim functionsList As Collection
Dim remarksList As Collection
Set functionsList = GetFunctionsList(wsSettings, 4, 10) ' Column D
Set remarksList = GetRemarksList(wsSettings, 5, 10) ' Column E
If functionsList.Count = 0 Then
MsgBox "Please enter at least one Function/Job Classification in the 'Settings' sheet (column D starting from row 10).", vbExclamation
Exit Sub
End If
If remarksList.Count = 0 Then
MsgBox "Please enter at least one Remark/Notes in the 'Settings' sheet (column E starting from row 10).", vbExclamation
Exit Sub
End If
' Define tasks with their probabilities and duration ranges
' Ensure that the number of tasks matches the entries in Settings
Dim taskNames As Variant
Dim taskWeights As Variant
Dim taskMinDurations As Variant
Dim taskMaxDurations As Variant
Dim numTasks As Integer
' Initialize task arrays
taskNames = Array("Checking Organization Records", "Creating Organization Records", "Email Management", _
"PowerBi", "Updating Organization", "Uploading Edocs", "Verifying Temporary Accounts", "OBPI Adhoc")
taskWeights = Array(80, 10, 80, 40, 30, 60, 80, 10) ' Corresponding to weights
taskMinDurations = Array(1, 10, 2, 2, 5, 1, 1, 10)
taskMaxDurations = Array(3, 12, 3, 3, 6, 2, 2, 20)
numTasks = UBound(taskNames) - LBound(taskNames) + 1
' Validate that task arrays align with Settings entries
If numTasks <> functionsList.Count Or numTasks <> remarksList.Count Then
MsgBox "Mismatch between defined tasks and Settings entries. Please ensure they align.", vbExclamation
Exit Sub
End If
' Define total desired duration in minutes (7 hrs 30 mins to 7 hrs 35 mins)
Dim minTotalDuration As Double, maxTotalDuration As Double
minTotalDuration = 450 ' 7*60 + 30
maxTotalDuration = 455 ' 7*60 + 35
' Initialize variables for task generation
Dim currentTime As Date
currentTime = startTime
Dim totalDuration As Double
totalDuration = 0
' Define Breaks as arrays
Dim breakStarts(1 To 3) As Date
Dim breakDurations(1 To 3) As Double
breakStarts(1) = break1Start
breakDurations(1) = break1Duration
breakStarts(2) = lunchBreakStart
breakDurations(2) = lunchBreakDuration
breakStarts(3) = break2Start
breakDurations(3) = break2Duration
' Sort breaks by start time in ascending order
Dim i As Integer, j As Integer
Dim tempStart As Date, tempDuration As Double
For i = 1 To 2
For j = i + 1 To 3
If breakStarts(i) > breakStarts(j) Then
tempStart = breakStarts(i)
tempDuration = breakDurations(i)
breakStarts(i) = breakStarts(j)
breakDurations(i) = breakDurations(j)
breakStarts(j) = tempStart
breakDurations(j) = tempDuration
End If
Next j
Next i
' Initialize next break index
Dim nextBreak As Integer
nextBreak = 1
' Clear previous data in Task Tracker sheet (from row 2 down)
wsTracker.Range("A2:H" & wsTracker.Rows.Count).ClearContents
' Initialize random number generator
Randomize
' Start generating tasks
Dim taskRow As Long
taskRow = 2 ' Start from row 2
Do While totalDuration < minTotalDuration And orgCodes.Count > 0
' Select a random Org Code from the collection
Dim selectedOrg As String
Dim randIndex As Integer
randIndex = Int((orgCodes.Count) * Rnd + 1) ' Generate random index between 1 and orgCodes.Count
selectedOrg = orgCodes.Item(randIndex)
' Remove the selected Org Code from the collection to prevent reuse
orgCodes.Remove randIndex
' Select a Function based on weighted probabilities
Dim selectedTaskIndex As Integer
selectedTaskIndex = GetWeightedRandomTaskIndex(taskWeights, numTasks)
Dim selectedTask As String
selectedTask = taskNames(selectedTaskIndex)
' Get corresponding duration range
Dim minDuration As Integer, maxDuration As Integer
minDuration = taskMinDurations(selectedTaskIndex)
maxDuration = taskMaxDurations(selectedTaskIndex)
' Assign a random duration within the range
Dim taskDuration As Integer
taskDuration = Int((maxDuration - minDuration + 1) * Rnd + minDuration)
' Check if adding this duration would exceed maxTotalDuration
If (totalDuration + taskDuration) > maxTotalDuration Then
taskDuration = maxTotalDuration - totalDuration
If taskDuration <= 0 Then Exit Do
End If
' Check if task overlaps with a break
Dim potentialEndTime As Date
potentialEndTime = currentTime + (taskDuration / (24 * 60))
Dim overlap As Boolean
overlap = False
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
overlap = True
Exit For
End If
Next i
If overlap Then
' Advance current time to after the overlapping break
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
currentTime = breakStarts(i) + (breakDurations(i) / (24 * 60))
nextBreak = i + 1
Exit For
End If
Next i
GoTo ContinueLoop
End If
' Get the corresponding Remark for the selected Function
Dim funcRemark As String
funcRemark = GetRemarkForFunction(wsSettings, 4, 5, selectedTask)
' Write to Task Tracker sheet
With wsTracker
.Range("A" & taskRow).Value = Format(startTime, "m/d/yyyy h:mm AM/PM")
.Range("B" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy h:mm AM/PM")
.Range("C" & taskRow).Value = Format(currentTime, "h:mm AM/PM")
.Range("D" & taskRow).Value = Format(potentialEndTime, "h:mm AM/PM")
.Range("E" & taskRow).Value = taskDuration
.Range("F" & taskRow).Value = selectedOrg
.Range("G" & taskRow).Value = selectedTask
.Range("H" & taskRow).Value = funcRemark
End With
' Update variables
currentTime = potentialEndTime
totalDuration = totalDuration + taskDuration
taskRow = taskRow + 1
ContinueLoop:
Loop
code
' Optionally, format the Task Tracker sheet
With wsTracker
.Columns("A:H").AutoFit
' Format columns A, B as Date/Time and C, D as Time
.Columns("A").NumberFormat = "m/d/yyyy h:mm AM/PM"
.Columns("B").NumberFormat = "m/d/yyyy h:mm AM/PM"
.Columns("C").NumberFormat = "h:mm AM/PM"
.Columns("D").NumberFormat = "h:mm AM/PM"
End With
MsgBox "Tasks generated successfully in the 'Task Tracker' sheet.", vbInformation
End Sub
' Function to get Org Codes from a column starting from a specific row
Function GetOrgCodes(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim orgCodes As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
orgCodes.Add ws.Cells(i, col).Value
End If
Next i
Set GetOrgCodes = orgCodes
End Function
' Function to get Functions from a column starting from a specific row
Function GetFunctionsList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim funcList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
funcList.Add ws.Cells(i, col).Value
End If
Next i
Set GetFunctionsList = funcList
End Function
' Function to get Remarks from a column starting from a specific row
Function GetRemarksList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim remarksList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
remarksList.Add ws.Cells(i, col).Value
End If
Next i
Set GetRemarksList = remarksList
End Function
' Function to perform weighted random selection
' probabilities array contains weights
' numTasks is the number of tasks
Function GetWeightedRandomTaskIndex(probabilities As Variant, numTasks As Integer) As Integer
Dim totalWeight As Double
Dim i As Integer
totalWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
totalWeight = totalWeight + probabilities(i)
Next i
code
Dim randVal As Double
randVal = Rnd * totalWeight
Dim cumulativeWeight As Double
cumulativeWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
cumulativeWeight = cumulativeWeight + probabilities(i)
If randVal <= cumulativeWeight Then
GetWeightedRandomTaskIndex = i
Exit Function
End If
Next i
' In case of rounding errors
GetWeightedRandomTaskIndex = UBound(probabilities)
End Function
' Function to get Remark for a given Function
Function GetRemarkForFunction(ws As Worksheet, funcCol As Integer, remarkCol As Integer, functionName As String) As String
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, funcCol).End(xlUp).Row
Dim i As Long
For i = 10 To lastRow ' Starting from row 10
If Trim(ws.Cells(i, funcCol).Value) = Trim(functionName) Then
GetRemarkForFunction = ws.Cells(i, remarkCol).Value
Exit Function
End If
Next i
' If not found, return empty string
GetRemarkForFunction = ""
End Function
' VBA Code to Initialize Workbook and Generate Task Tracker
' Place this code in a standard module (Insert > Module) in the VBA editor.
Option Explicit
' Subroutine to initialize the workbook: create sheets, set up columns, add button
Sub InitializeTaskTracker()
Dim wsTaskTracker As Worksheet
Dim wsSettings As Worksheet
Dim shp As Shape
Dim btnLeft As Double, btnTop As Double, btnWidth As Double, btnHeight As Double
Dim btnName As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Attempt to set Task Tracker sheet; if it doesn't exist, create it
On Error Resume Next
Set wsTaskTracker = ThisWorkbook.Worksheets("Task Tracker")
On Error GoTo 0
If wsTaskTracker Is Nothing Then
Set wsTaskTracker = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
wsTaskTracker.Name = "Task Tracker"
Else
' Clear existing content
wsTaskTracker.Cells.Clear
End If
' Attempt to set Settings sheet; if it doesn't exist, create it
On Error Resume Next
Set wsSettings = ThisWorkbook.Worksheets("Settings")
On Error GoTo 0
If wsSettings Is Nothing Then
Set wsSettings = ThisWorkbook.Worksheets.Add(After:=wsTaskTracker)
wsSettings.Name = "Settings"
Else
' Clear existing content
wsSettings.Cells.Clear
End If
' Set up columns in Task Tracker
With wsTaskTracker
.Range("A1").Value = "Date Offered"
.Range("B1").Value = "Date Completed"
.Range("C1").Value = "Time Started"
.Range("D1").Value = "Time Finished"
.Range("E1").Value = "Duration (hh:mm:ss)"
.Range("F1").Value = "Reference Number"
.Range("G1").Value = "Function/Job Classification"
.Range("H1").Value = "Remarks/Notes"
' Format header as bold and apply background color
With .Range("A1:H1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:H").AutoFit
End With
' Set up Settings sheet
With wsSettings
' Define parameters and labels
.Range("A1").Value = "Parameter"
.Range("B1").Value = "Value"
.Range("A2").Value = "Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B2").Value = "10/5/2023 8:00 AM" ' Example start time
.Range("A3").Value = "First Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B3").Value = "10/5/2023 10:00 AM"
.Range("A4").Value = "First Break Duration (mins)"
.Range("B4").Value = 13
.Range("A5").Value = "Lunch Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B5").Value = "10/5/2023 12:30 PM"
.Range("A6").Value = "Lunch Break Duration (mins)"
.Range("B6").Value = 55
.Range("A7").Value = "Last Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B7").Value = "10/5/2023 3:30 PM"
.Range("A8").Value = "Last Break Duration (mins)"
.Range("B8").Value = 15
' Headers for Org Codes, Functions, and Remarks
.Range("C9").Value = "Org Codes"
.Range("D9").Value = "Function/Job Classification"
.Range("E9").Value = "Remarks/Notes"
With .Range("C9:E9")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Example Org Codes
.Range("C10").Value = "ORG001"
.Range("C11").Value = "ORG002"
.Range("C12").Value = "ORG003"
' Add more Org Codes as needed
' Example Functions and Remarks
.Range("D10").Value = "Checking Organization Records"
.Range("D11").Value = "Creating Organization Records"
.Range("D12").Value = "Email Management"
.Range("D13").Value = "PowerBi"
.Range("D14").Value = "Updating Organization"
.Range("D15").Value = "Uploading Edocs"
.Range("D16").Value = "Verifying Temporary Accounts"
.Range("D17").Value = "OBPI Adhoc"
.Range("E10").Value = "Remark for Checking Organization Records"
.Range("E11").Value = "Remark for Creating Organization Records"
.Range("E12").Value = "Remark for Email Management"
.Range("E13").Value = "Remark for PowerBi"
.Range("E14").Value = "Remark for Updating Organization"
.Range("E15").Value = "Remark for Uploading Edocs"
.Range("E16").Value = "Remark for Verifying Temporary Accounts"
.Range("E17").Value = "Remark for OBPI Adhoc"
' Add more Remarks as needed
' Format headers for Parameter
With .Range("A1:B1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:E").AutoFit
End With
' Remove existing "Generate Tasks" button if it exists
btnName = "btnGenerateTasks"
On Error Resume Next
wsTaskTracker.Shapes(btnName).Delete
On Error GoTo 0
' Add a button to Task Tracker sheet to run GenerateTasks macro using Shapes.AddFormControl
With wsTaskTracker
' Define button dimensions and position
btnLeft = 10
btnTop = 10
btnWidth = 120
btnHeight = 30
' Add the button as a Form Control
Set shp = .Shapes.AddFormControl(Type:=xlButtonControl, Left:=btnLeft, Top:=btnTop, Width:=btnWidth, Height:=btnHeight)
With shp
.OnAction = "GenerateTasks"
.Name = btnName
.TextFrame.Characters.Text = "Generate Tasks"
.TextFrame.HorizontalAlignment = xlHAlignCenter
.TextFrame.VerticalAlignment = xlVAlignCenter
.Fill.ForeColor.RGB = RGB(0, 112, 192) ' Optional: Button color
.Fill.Transparency = 0
.Line.Visible = msoFalse ' Optional: Remove button border
.TextFrame.Characters.Font.Color = RGB(255, 255, 255) ' Optional: Text color
.TextFrame.Characters.Font.Bold = True
End With
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Workbook initialized successfully! Please configure the 'Settings' sheet before generating tasks.", vbInformation
End Sub
' Subroutine to generate tasks based on Settings
Sub GenerateTasks()
Dim wsTracker As Worksheet
Dim wsSettings As Worksheet
Set wsTracker = ThisWorkbook.Worksheets("Task Tracker")
Set wsSettings = ThisWorkbook.Worksheets("Settings")
' Read Start Time
Dim startTime As Date
If IsDate(wsSettings.Range("B2").Value) Then
startTime = wsSettings.Range("B2").Value
Else
MsgBox "Please enter a valid Start Time in the 'Settings' sheet (cell B2).", vbExclamation
Exit Sub
End If
' Read Break Start Times and Durations
Dim break1Start As Date, break1Duration As Double
Dim lunchBreakStart As Date, lunchBreakDuration As Double
Dim break2Start As Date, break2Duration As Double
If IsDate(wsSettings.Range("B3").Value) Then
break1Start = wsSettings.Range("B3").Value
Else
MsgBox "Please enter a valid First Break Start Time in the 'Settings' sheet (cell B3).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B4").Value) Then
break1Duration = wsSettings.Range("B4").Value
Else
MsgBox "Please enter a valid First Break Duration in minutes in the 'Settings' sheet (cell B4).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B5").Value) Then
lunchBreakStart = wsSettings.Range("B5").Value
Else
MsgBox "Please enter a valid Lunch Break Start Time in the 'Settings' sheet (cell B5).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B6").Value) Then
lunchBreakDuration = wsSettings.Range("B6").Value
Else
MsgBox "Please enter a valid Lunch Break Duration in minutes in the 'Settings' sheet (cell B6).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B7").Value) Then
break2Start = wsSettings.Range("B7").Value
Else
MsgBox "Please enter a valid Last Break Start Time in the 'Settings' sheet (cell B7).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B8").Value) Then
break2Duration = wsSettings.Range("B8").Value
Else
MsgBox "Please enter a valid Last Break Duration in minutes in the 'Settings' sheet (cell B8).", vbExclamation
Exit Sub
End If
' Read Org Codes from Settings, Column C, starting from C10 down
Dim orgCodes As Collection
Set orgCodes = GetOrgCodes(wsSettings, 3, 10) ' Column C, starting from row 10
If orgCodes.Count = 0 Then
MsgBox "Please enter at least one Org Code in the 'Settings' sheet (column C starting from row 10).", vbExclamation
Exit Sub
End If
' Read Functions and Remarks from Settings, Columns D and E, starting from D10 and E10
Dim functionsList As Collection
Dim remarksList As Collection
Set functionsList = GetFunctionsList(wsSettings, 4, 10) ' Column D
Set remarksList = GetRemarksList(wsSettings, 5, 10) ' Column E
If functionsList.Count = 0 Then
MsgBox "Please enter at least one Function/Job Classification in the 'Settings' sheet (column D starting from row 10).", vbExclamation
Exit Sub
End If
If remarksList.Count = 0 Then
MsgBox "Please enter at least one Remark/Notes in the 'Settings' sheet (column E starting from row 10).", vbExclamation
Exit Sub
End If
' Define tasks with their probabilities and duration ranges
Dim taskNames As Variant
Dim taskWeights As Variant
Dim taskMinDurations As Variant
Dim taskMaxDurations As Variant
Dim numTasks As Integer
' Initialize task arrays
taskNames = Array("Checking Organization Records", "Creating Organization Records", "Email Management", _
"PowerBi", "Updating Organization", "Uploading Edocs", "Verifying Temporary Accounts", "OBPI Adhoc")
taskWeights = Array(80, 10, 80, 40, 30, 60, 80, 10) ' Corresponding to weights
taskMinDurations = Array(1, 10, 2, 2, 5, 1, 1, 10) ' Random range min (inclusive)
taskMaxDurations = Array(3, 12, 3, 3, 6, 2, 2, 20) ' Random range max (inclusive)
numTasks = UBound(taskNames) - LBound(taskNames) + 1
' Validate that task arrays align with Settings entries
If numTasks <> functionsList.Count Or numTasks <> remarksList.Count Then
MsgBox "Mismatch between defined tasks and Settings entries. Please ensure they align.", vbExclamation
Exit Sub
End If
' Define total desired duration in minutes (7 hrs 30 mins to 7 hrs 35 mins)
Dim minTotalDuration As Double, maxTotalDuration As Double
minTotalDuration = 450 ' 7*60 + 30
maxTotalDuration = 455 ' 7*60 + 35
' Initialize variables for task generation
Dim currentTime As Date
currentTime = startTime
Dim totalDuration As Double
totalDuration = 0
' Define Breaks as arrays
Dim breakStarts(1 To 3) As Date
Dim breakDurations(1 To 3) As Double
breakStarts(1) = break1Start
breakDurations(1) = break1Duration
breakStarts(2) = lunchBreakStart
breakDurations(2) = lunchBreakDuration
breakStarts(3) = break2Start
breakDurations(3) = break2Duration
' Sort breaks by start time in ascending order
Dim i As Integer, j As Integer
Dim tempStart As Date, tempDuration As Double
For i = 1 To 2
For j = i + 1 To 3
If breakStarts(i) > breakStarts(j) Then
tempStart = breakStarts(i)
tempDuration = breakDurations(i)
breakStarts(i) = breakStarts(j)
breakDurations(i) = breakDurations(j)
breakStarts(j) = tempStart
breakDurations(j) = tempDuration
End If
Next j
Next i
' Initialize next break index
Dim nextBreak As Integer
nextBreak = 1
' Clear previous data in Task Tracker sheet (from row 2 down)
wsTracker.Range("A2:H" & wsTracker.Rows.Count).ClearContents
' Initialize random number generator
Randomize
' Start generating tasks
Dim taskRow As Long
taskRow = 2 ' Start from row 2
Do While totalDuration < minTotalDuration And orgCodes.Count > 0
Dim selectedOrg As String
Dim randIndex As Integer
randIndex = Int((orgCodes.Count) * Rnd + 1)
selectedOrg = orgCodes.Item(randIndex)
orgCodes.Remove randIndex
Dim selectedTaskIndex As Integer
selectedTaskIndex = GetWeightedRandomTaskIndex(taskWeights, numTasks)
Dim selectedTask As String
selectedTask = taskNames(selectedTaskIndex)
Dim minDuration As Integer, maxDuration As Integer
minDuration = taskMinDurations(selectedTaskIndex)
maxDuration = taskMaxDurations(selectedTaskIndex)
Dim taskDuration As Double
taskDuration = minDuration + Rnd * (maxDuration - minDuration) + (Rnd * 60) / 100
If (totalDuration + taskDuration) > maxTotalDuration Then
taskDuration = maxTotalDuration - totalDuration
If taskDuration <= 0 Then Exit Do
End If
Dim ms As Long
ms = CLng(Rnd * 1000)
Dim potentialEndTime As Date
potentialEndTime = DateAdd("s", taskDuration * 60 + ms / 1000, currentTime)
Dim overlap As Boolean
overlap = False
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
overlap = True
Exit For
End If
Next i
If overlap Then
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
currentTime = breakStarts(i) + (breakDurations(i) / (24 * 60))
nextBreak = i + 1
Exit For
End If
Next i
GoTo ContinueLoop
End If
Dim funcRemark As String
funcRemark = GetRemarkForFunction(wsSettings, 4, 5, selectedTask)
With wsTracker
.Range("A" & taskRow).Value = Format(currentTime, "m/d/yyyy") ' Date Offered
.Range("B" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy") ' Date Completed
.Range("C" & taskRow).Value = Format(currentTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Started
.Range("D" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Finished
.Range("E" & taskRow).Value = Format(TimeSerial(0, 0, taskDuration * 60), "hh:mm:ss") & _
Format(ms, ".000") ' Duration formatted
.Range("F" & taskRow).Value = selectedOrg
.Range("G" & taskRow).Value = selectedTask
.Range("H" & taskRow).Value = funcRemark
End With
currentTime = DateAdd("s", (Rnd * 3), potentialEndTime) ' Add delay of 1 to 3 seconds before next start
totalDuration = totalDuration + taskDuration
taskRow = taskRow + 1
ContinueLoop:
Loop
With wsTracker
.Columns("A:H").AutoFit
.Columns("A").NumberFormat = "m/d/yyyy"
.Columns("B").NumberFormat = "m/d/yyyy"
.Columns("C").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM"
.Columns("D").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM"
End With
MsgBox "Tasks generated successfully in the 'Task Tracker' sheet.", vbInformation
End Sub
' Function to get Org Codes from a column starting from a specific row
Function GetOrgCodes(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim orgCodes As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
orgCodes.Add ws.Cells(i, col).Value
End If
Next i
Set GetOrgCodes = orgCodes
End Function
' Function to get Functions from a column starting from a specific row
Function GetFunctionsList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim funcList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
funcList.Add ws.Cells(i, col).Value
End If
Next i
Set GetFunctionsList = funcList
End Function
' Function to get Remarks from a column starting from a specific row
Function GetRemarksList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim remarksList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
remarksList.Add ws.Cells(i, col).Value
End If
Next i
Set GetRemarksList = remarksList
End Function
' Function to perform weighted random selection
' probabilities array contains weights
' numTasks is the number of tasks
Function GetWeightedRandomTaskIndex(probabilities As Variant, numTasks As Integer) As Integer
Dim totalWeight As Double
Dim i As Integer
totalWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
totalWeight = totalWeight + probabilities(i)
Next i
Dim randVal As Double
randVal = Rnd * totalWeight
Dim cumulativeWeight As Double
cumulativeWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
cumulativeWeight = cumulativeWeight + probabilities(i)
If randVal <= cumulativeWeight Then
GetWeightedRandomTaskIndex = i
Exit Function
End If
Next i
' In case of rounding errors
GetWeightedRandomTaskIndex = UBound(probabilities)
End Function
' Function to get Remark for a given Function
Function GetRemarkForFunction(ws As Worksheet, funcCol As Integer, remarkCol As Integer, functionName As String) As String
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, funcCol).End(xlUp).Row
Dim i As Long
For i = 10 To lastRow ' Starting from row 10
If Trim(ws.Cells(i, funcCol).Value) = Trim(functionName) Then
GetRemarkForFunction = ws.Cells(i, remarkCol).Value
Exit Function
End If
Next i
' If not found, return empty string
GetRemarkForFunction = ""
End Function
Key Adjustments:
Milliseconds Integration: Uses milliseconds for task duration and start intervals (employing a millisecond division from random seconds).
Randomization: Task duration includes random milliseconds, and durations respect the specified ranges.
Formatting: Ensures all times display up to milliseconds, and calculated durations reflect the desired format.
This code generates tasks with more realistic and varied durations using milliseconds. It aligns with the sample provided to achieve granular time tracking.
' VBA Code to Initialize Workbook and Generate Task Tracker
' Place this code in a standard module (Insert > Module) in the VBA editor.
Option Explicit
' Subroutine to initialize the workbook: create sheets, set up columns, add button
Sub InitializeTaskTracker()
Dim wsTaskTracker As Worksheet
Dim wsSettings As Worksheet
Dim shp As Shape
Dim btnLeft As Double, btnTop As Double, btnWidth As Double, btnHeight As Double
Dim btnName As String
Application.ScreenUpdating = False
Application.DisplayAlerts = False
' Attempt to set Task Tracker sheet; if it doesn't exist, create it
On Error Resume Next
Set wsTaskTracker = ThisWorkbook.Worksheets("Task Tracker")
On Error GoTo 0
If wsTaskTracker Is Nothing Then
Set wsTaskTracker = ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count))
wsTaskTracker.Name = "Task Tracker"
Else
' Clear existing content
wsTaskTracker.Cells.Clear
End If
' Attempt to set Settings sheet; if it doesn't exist, create it
On Error Resume Next
Set wsSettings = ThisWorkbook.Worksheets("Settings")
On Error GoTo 0
If wsSettings Is Nothing Then
Set wsSettings = ThisWorkbook.Worksheets.Add(After:=wsTaskTracker)
wsSettings.Name = "Settings"
Else
' Clear existing content
wsSettings.Cells.Clear
End If
' Set up columns in Task Tracker
With wsTaskTracker
.Range("A1").Value = "Date Offered"
.Range("B1").Value = "Date Completed"
.Range("C1").Value = "Time Started"
.Range("D1").Value = "Time Finished"
.Range("E1").Value = "Duration (hh:mm:ss AM/PM)"
.Range("F1").Value = "Reference Number"
.Range("G1").Value = "Function/Job Classification"
.Range("H1").Value = "Remarks/Notes"
' Format header as bold and apply background color
With .Range("A1:H1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:H").AutoFit
End With
' Set up Settings sheet
With wsSettings
' Define parameters and labels
.Range("A1").Value = "Parameter"
.Range("B1").Value = "Value"
.Range("A2").Value = "Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B2").Value = "10/5/2023 8:00 AM" ' User should modify as needed
.Range("A3").Value = "First Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B3").Value = "10/5/2023 10:00 AM"
.Range("A4").Value = "First Break Duration (mins)"
.Range("B4").Value = 13
.Range("A5").Value = "Lunch Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B5").Value = "10/5/2023 12:30 PM"
.Range("A6").Value = "Lunch Break Duration (mins)"
.Range("B6").Value = 55
.Range("A7").Value = "Last Break Start Time (m/d/yyyy h:mm AM/PM)"
.Range("B7").Value = "10/5/2023 3:30 PM"
.Range("A8").Value = "Last Break Duration (mins)"
.Range("B8").Value = 15
' Headers for Org Codes, Functions, and Remarks
.Range("C9").Value = "Org Codes"
.Range("D9").Value = "Function/Job Classification"
.Range("E9").Value = "Remarks/Notes"
With .Range("C9:E9")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Example Org Codes
.Range("C10").Value = "ORG001"
.Range("C11").Value = "ORG002"
.Range("C12").Value = "ORG003"
' Add more Org Codes as needed
' Example Functions and Remarks
.Range("D10").Value = "Checking Organization Records"
.Range("D11").Value = "Creating Organization Records"
.Range("D12").Value = "Email Management"
.Range("D13").Value = "PowerBi"
.Range("D14").Value = "Updating Organization"
.Range("D15").Value = "Uploading Edocs"
.Range("D16").Value = "Verifying Temporary Accounts"
.Range("D17").Value = "OBPI Adhoc"
.Range("E10").Value = "Remark for Checking Organization Records"
.Range("E11").Value = "Remark for Creating Organization Records"
.Range("E12").Value = "Remark for Email Management"
.Range("E13").Value = "Remark for PowerBi"
.Range("E14").Value = "Remark for Updating Organization"
.Range("E15").Value = "Remark for Uploading Edocs"
.Range("E16").Value = "Remark for Verifying Temporary Accounts"
.Range("E17").Value = "Remark for OBPI Adhoc"
' Add more Remarks as needed
' Format headers for Parameter
With .Range("A1:B1")
.Font.Bold = True
.Interior.Color = RGB(200, 200, 200)
End With
' Adjust column widths
.Columns("A:E").AutoFit
End With
' Remove existing "Generate Tasks" button if it exists
btnName = "btnGenerateTasks"
On Error Resume Next
wsTaskTracker.Shapes(btnName).Delete
On Error GoTo 0
' Add a button to Task Tracker sheet to run GenerateTasks macro using Shapes.AddFormControl
With wsTaskTracker
' Define button dimensions and position
btnLeft = 10
btnTop = 10
btnWidth = 120
btnHeight = 30
' Add the button as a Form Control
Set shp = .Shapes.AddFormControl(Type:=xlButtonControl, Left:=btnLeft, Top:=btnTop, Width:=btnWidth, Height:=btnHeight)
With shp
.OnAction = "GenerateTasks"
.Name = btnName
.TextFrame.Characters.Text = "Generate Tasks"
.TextFrame.HorizontalAlignment = xlHAlignCenter
.TextFrame.VerticalAlignment = xlVAlignCenter
.Fill.ForeColor.RGB = RGB(0, 112, 192) ' Optional: Button color
.Fill.Transparency = 0
.Line.Visible = msoFalse ' Optional: Remove button border
.TextFrame.Characters.Font.Color = RGB(255, 255, 255) ' Optional: Text color
.TextFrame.Characters.Font.Bold = True
End With
End With
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Workbook initialized successfully! Please configure the 'Settings' sheet before generating tasks.", vbInformation
End Sub
' Subroutine to generate tasks based on Settings
Sub GenerateTasks()
Dim wsTracker As Worksheet
Dim wsSettings As Worksheet
Set wsTracker = ThisWorkbook.Worksheets("Task Tracker")
Set wsSettings = ThisWorkbook.Worksheets("Settings")
' Read Start Time
Dim startTime As Date
If IsDate(wsSettings.Range("B2").Value) Then
startTime = wsSettings.Range("B2").Value
Else
MsgBox "Please enter a valid Start Time in the 'Settings' sheet (cell B2).", vbExclamation
Exit Sub
End If
' Read Break Start Times and Durations
Dim break1Start As Date, break1Duration As Double
Dim lunchBreakStart As Date, lunchBreakDuration As Double
Dim break2Start As Date, break2Duration As Double
If IsDate(wsSettings.Range("B3").Value) Then
break1Start = wsSettings.Range("B3").Value
Else
MsgBox "Please enter a valid First Break Start Time in the 'Settings' sheet (cell B3).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B4").Value) Then
break1Duration = wsSettings.Range("B4").Value
Else
MsgBox "Please enter a valid First Break Duration in minutes in the 'Settings' sheet (cell B4).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B5").Value) Then
lunchBreakStart = wsSettings.Range("B5").Value
Else
MsgBox "Please enter a valid Lunch Break Start Time in the 'Settings' sheet (cell B5).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B6").Value) Then
lunchBreakDuration = wsSettings.Range("B6").Value
Else
MsgBox "Please enter a valid Lunch Break Duration in minutes in the 'Settings' sheet (cell B6).", vbExclamation
Exit Sub
End If
If IsDate(wsSettings.Range("B7").Value) Then
break2Start = wsSettings.Range("B7").Value
Else
MsgBox "Please enter a valid Last Break Start Time in the 'Settings' sheet (cell B7).", vbExclamation
Exit Sub
End If
If IsNumeric(wsSettings.Range("B8").Value) Then
break2Duration = wsSettings.Range("B8").Value
Else
MsgBox "Please enter a valid Last Break Duration in minutes in the 'Settings' sheet (cell B8).", vbExclamation
Exit Sub
End If
' Read Org Codes from Settings, Column C, starting from C10 down
Dim orgCodes As Collection
Set orgCodes = GetOrgCodes(wsSettings, 3, 10) ' Column C, starting from row 10
If orgCodes.Count = 0 Then
MsgBox "Please enter at least one Org Code in the 'Settings' sheet (column C starting from row 10).", vbExclamation
Exit Sub
End If
' Read Functions and Remarks from Settings, Columns D and E, starting from D10 and E10
Dim functionsList As Collection
Dim remarksList As Collection
Set functionsList = GetFunctionsList(wsSettings, 4, 10) ' Column D
Set remarksList = GetRemarksList(wsSettings, 5, 10) ' Column E
If functionsList.Count = 0 Then
MsgBox "Please enter at least one Function/Job Classification in the 'Settings' sheet (column D starting from row 10).", vbExclamation
Exit Sub
End If
If remarksList.Count = 0 Then
MsgBox "Please enter at least one Remark/Notes in the 'Settings' sheet (column E starting from row 10).", vbExclamation
Exit Sub
End If
' Define tasks with their probabilities and duration ranges
Dim taskNames As Variant
Dim taskWeights As Variant
Dim taskMinDurations As Variant
Dim taskMaxDurations As Variant
Dim numTasks As Integer
' Initialize task arrays
taskNames = Array("Checking Organization Records", "Creating Organization Records", "Email Management", _
"PowerBi", "Updating Organization", "Uploading Edocs", "Verifying Temporary Accounts", "OBPI Adhoc")
taskWeights = Array(80, 10, 80, 40, 30, 60, 80, 10) ' Corresponding to weights
taskMinDurations = Array(1, 10, 2, 2, 5, 1, 1, 10) ' Random range min (inclusive)
taskMaxDurations = Array(3, 12, 3, 3, 6, 2, 2, 20) ' Random range max (inclusive)
numTasks = UBound(taskNames) - LBound(taskNames) + 1
' Validate that task arrays align with Settings entries
If numTasks <> functionsList.Count Or numTasks <> remarksList.Count Then
MsgBox "Mismatch between defined tasks and Settings entries. Please ensure they align.", vbExclamation
Exit Sub
End If
' Define total desired duration in minutes (7 hrs 30 mins to 7 hrs 35 mins)
Dim minTotalDuration As Double, maxTotalDuration As Double
minTotalDuration = 450 ' 7*60 + 30
maxTotalDuration = 455 ' 7*60 + 35
' Initialize variables for task generation
Dim currentTime As Date
currentTime = startTime
Dim totalDuration As Double
totalDuration = 0
' Define Breaks as arrays
Dim breakStarts(1 To 3) As Date
Dim breakDurations(1 To 3) As Double
breakStarts(1) = break1Start
breakDurations(1) = break1Duration
breakStarts(2) = lunchBreakStart
breakDurations(2) = lunchBreakDuration
breakStarts(3) = break2Start
breakDurations(3) = break2Duration
' Sort breaks by start time in ascending order
Dim i As Integer, j As Integer
Dim tempStart As Date, tempDuration As Double
For i = 1 To 2
For j = i + 1 To 3
If breakStarts(i) > breakStarts(j) Then
tempStart = breakStarts(i)
tempDuration = breakDurations(i)
breakStarts(i) = breakStarts(j)
breakDurations(i) = breakDurations(j)
breakStarts(j) = tempStart
breakDurations(j) = tempDuration
End If
Next j
Next i
' Initialize next break index
Dim nextBreak As Integer
nextBreak = 1
' Clear previous data in Task Tracker sheet (from row 2 down)
wsTracker.Range("A2:H" & wsTracker.Rows.Count).ClearContents
' Initialize random number generator
Randomize
' Start generating tasks
Dim taskRow As Long
taskRow = 2 ' Start from row 2
Do While totalDuration < minTotalDuration And orgCodes.Count > 0
Dim selectedOrg As String
Dim randIndex As Integer
randIndex = Int((orgCodes.Count) * Rnd + 1)
selectedOrg = orgCodes.Item(randIndex)
orgCodes.Remove randIndex
Dim selectedTaskIndex As Integer
selectedTaskIndex = GetWeightedRandomTaskIndex(taskWeights, numTasks)
Dim selectedTask As String
selectedTask = taskNames(selectedTaskIndex)
Dim minDuration As Integer, maxDuration As Integer
minDuration = taskMinDurations(selectedTaskIndex)
maxDuration = taskMaxDurations(selectedTaskIndex)
Dim taskDuration As Double
taskDuration = minDuration + Rnd * (maxDuration - minDuration) + (Rnd * 60) / 100
If (totalDuration + taskDuration) > maxTotalDuration Then
taskDuration = maxTotalDuration - totalDuration
If taskDuration <= 0 Then Exit Do
End If
Dim ms As Long
ms = CLng(Rnd * 1000)
Dim potentialEndTime As Date
potentialEndTime = DateAdd("s", taskDuration * 60 + ms / 1000, currentTime)
Dim overlap As Boolean
overlap = False
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
overlap = True
Exit For
End If
Next i
If overlap Then
For i = nextBreak To 3
If (currentTime < breakStarts(i) + (breakDurations(i) / (24 * 60))) And (potentialEndTime > breakStarts(i)) Then
currentTime = breakStarts(i) + (breakDurations(i) / (24 * 60))
nextBreak = i + 1
Exit For
End If
Next i
GoTo ContinueLoop
End If
Dim funcRemark As String
funcRemark = GetRemarkForFunction(wsSettings, 4, 5, selectedTask)
With wsTracker
.Range("A" & taskRow).Value = Format(currentTime, "m/d/yyyy") ' Date Offered
.Range("B" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy") ' Date Completed
.Range("C" & taskRow).Value = Format(currentTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Started
.Range("D" & taskRow).Value = Format(potentialEndTime, "m/d/yyyy h:mm:ss.000 AM/PM") ' Time Finished
.Range("E" & taskRow).Value = Format((taskDuration * 60) / (24 * 60 * 60), "hh:mm:ss AM/PM") ' Duration formatted
.Range("F" & taskRow).Value = selectedOrg
.Range("G" & taskRow).Value = selectedTask
.Range("H" & taskRow).Value = funcRemark
End With
currentTime = DateAdd("s", (Rnd * 3), potentialEndTime) ' Add delay of 1 to 3 seconds before next start
totalDuration = totalDuration + taskDuration
taskRow = taskRow + 1
ContinueLoop:
Loop
With wsTracker
.Columns("A:H").AutoFit
.Columns("A").NumberFormat = "m/d/yyyy"
.Columns("B").NumberFormat = "m/d/yyyy"
.Columns("C").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM"
.Columns("D").NumberFormat = "m/d/yyyy h:mm:ss.000 AM/PM"
.Columns("E").NumberFormat = "hh:mm:ss AM/PM" ' Ensure proper formatting
End With
MsgBox "Tasks generated successfully in the 'Task Tracker' sheet.", vbInformation
End Sub
' Function to get Org Codes from a column starting from a specific row
Function GetOrgCodes(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim orgCodes As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
orgCodes.Add ws.Cells(i, col).Value
End If
Next i
Set GetOrgCodes = orgCodes
End Function
' Function to get Functions from a column starting from a specific row
Function GetFunctionsList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim funcList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
funcList.Add ws.Cells(i, col).Value
End If
Next i
Set GetFunctionsList = funcList
End Function
' Function to get Remarks from a column starting from a specific row
Function GetRemarksList(ws As Worksheet, col As Integer, startRow As Integer) As Collection
Dim remarksList As New Collection
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, col).End(xlUp).Row
Dim i As Long
For i = startRow To lastRow
If Trim(ws.Cells(i, col).Value) <> "" Then
remarksList.Add ws.Cells(i, col).Value
End If
Next i
Set GetRemarksList = remarksList
End Function
' Function to perform weighted random selection
' probabilities array contains weights
' numTasks is the number of tasks
Function GetWeightedRandomTaskIndex(probabilities As Variant, numTasks As Integer) As Integer
Dim totalWeight As Double
Dim i As Integer
totalWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
totalWeight = totalWeight + probabilities(i)
Next i
Dim randVal As Double
randVal = Rnd * totalWeight
Dim cumulativeWeight As Double
cumulativeWeight = 0
For i = LBound(probabilities) To UBound(probabilities)
cumulativeWeight = cumulativeWeight + probabilities(i)
If randVal <= cumulativeWeight Then
GetWeightedRandomTaskIndex = i
Exit Function
End If
Next i
' In case of rounding errors
GetWeightedRandomTaskIndex = UBound(probabilities)
End Function
' Function to get Remark for a given Function
Function GetRemarkForFunction(ws As Worksheet, funcCol As Integer, remarkCol As Integer, functionName As String) As String
Dim lastRow As Long
lastRow = ws.Cells(ws.Rows.Count, funcCol).End(xlUp).Row
Dim i As Long
For i = 10 To lastRow ' Starting from row 10
If Trim(ws.Cells(i, funcCol).Value) = Trim(functionName) Then
GetRemarkForFunction = ws.Cells(i, remarkCol).Value
Exit Function
End If
Next i
' If not found, return empty string
GetRemarkForFunction = ""
End Function
Key Changes:
Duration Formatting: Duration is calculated as a time value (taskDuration * 60) / (24 * 60 * 60) and formatted using "hh:mm:ss AM/PM".
This code will display the duration in the desired "hh:mm:ss AM/PM" format, aligning with your example.