我在 Excel 中有两个表格,一个名为“Calendar”,另一个名为“PlanTable”。
我正在尝试根据当天某台机器的计划来计算每个工人应该做多少工作。
示例:
假设我们以 2024 年 7 月 1 日为例。在右表中,当天机器(在“Utilaj”列下)R1、R3 和 R9 工作,每台机器旁边是当天的计划(在“计划”列下)。
之后,我们检查右表,了解有多少工人被分配到 R1、R3 以及 R9 机器。
发现2024年7月1日,R1有2名工人,R3有1名工人,R9有3名工人。
每个工人旁边的值应该是(机器的计划/在特定日期在该机器上工作的工人数量)。
我成功地做到了这一点,但是当我将一个新人放入“日历”表中时,这些值不会随工人一起移动。
第四个按钮“Calculeaza Fapt”的代码。
Sub Refresh()
On Error GoTo ErrorHandler
Dim ws As Worksheet
Dim planTbl As ListObject
Dim calendarTbl As ListObject
Dim selectedDate As String
Dim utilaj As String
Dim r As Range
Dim cell As Range
Dim workerCount As Long
Dim planValue As Double
Dim faptValue As Double
Dim workerDict As Object
Dim utilajKey As Variant
Set ws = ThisWorkbook.Sheets("Sheet1")
Set planTbl = ws.ListObjects("PlanTable")
Set calendarTbl = ws.ListObjects("Calendar")
' Initialize dictionary to count workers
Set workerDict = CreateObject("Scripting.Dictionary")
' Loop through the dates in the PlanTable
For Each r In planTbl.ListColumns("Data").DataBodyRange
selectedDate = Format(r.Value, "dd-mmm-yy")
Debug.Print "Processing date: " & selectedDate
' Reset workerDict for each date
workerDict.RemoveAll
' Count the number of workers for each Utilaj on the selected date from the Calendar table
For Each cell In calendarTbl.ListColumns("Data").DataBodyRange
If Format(cell.Value, "dd-mmm-yy") = selectedDate Then
utilaj = cell.Offset(0, calendarTbl.ListColumns("Utilaj").Index - calendarTbl.ListColumns("Data").Index).Value
If workerDict.exists(utilaj) Then
workerDict(utilaj) = workerDict(utilaj) + 1
Else
workerDict.Add utilaj, 1
End If
End If
Next cell
' Debugging output
For Each utilajKey In workerDict.Keys
Debug.Print "Utilaj: " & utilajKey & ", Workers: " & workerDict(utilajKey)
Next utilajKey
' Divide the Plan value by the number of workers and assign to the Fapt column in the Calendar table
utilaj = r.Offset(0, planTbl.ListColumns("Utilaj").Index - planTbl.ListColumns("Data").Index).Value
planValue = r.Offset(0, planTbl.ListColumns("Plan").Index - planTbl.ListColumns("Data").Index).Value
If workerDict.exists(utilaj) Then
workerCount = workerDict(utilaj)
faptValue = planValue / workerCount
' Update the Calendar table
For Each cell In calendarTbl.ListColumns("Data").DataBodyRange
If Format(cell.Value, "dd-mmm-yy") = selectedDate And _
cell.Offset(0, calendarTbl.ListColumns("Utilaj").Index - calendarTbl.ListColumns("Data").Index).Value = utilaj Then
cell.Offset(0, calendarTbl.ListColumns("Plan").Index - calendarTbl.ListColumns("Data").Index).Value = faptValue
End If
Next cell
Debug.Print "Assigned Fapt value: " & faptValue & " to Utilaj: " & utilaj
Else
Debug.Print "No workers found for Utilaj: " & utilaj & " on date: " & selectedDate
End If
Next r
MsgBox "Values updated successfully!"
Exit Sub
ErrorHandler:
MsgBox "Error " & Err.Number & ": " & Err.Description
End Sub