|
这种OK?
- Sub DistributeHoursForMultipleProjects()
- Dim ws As Worksheet
- Dim inputMonth As String
- Dim totalHours As Long
- Dim workDayCount As Long
- Dim currentDay As Long
- Dim remainingHours As Long
- Dim dailyHours As Long
- Dim monthStart As Date
- Dim monthEnd As Date
- Dim currentDate As Date
- Dim projectRow As Long
- Dim lastRow As Long
- Dim outputCol As Long
-
- ' 设置工作表
- Set ws = ThisWorkbook.Sheets("Sheet1")
-
- ' 清空之前的记录
- ws.Range("C5:AG40").ClearContents
-
- ' 获取输入的月份
- inputMonth = ws.Range("A2").Value
-
- ' 获取最后一行
- lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
-
- ' 遍历每个项目
- For projectRow = 5 To lastRow ' 假设项目从A5开始
- ' 获取对应项目的总工时
- totalHours = ws.Cells(projectRow, 2).Value
-
- ' 检查输入格式是否正确
- On Error Resume Next
- monthStart = CDate(inputMonth & "/01/2024") ' 假设2024年,实际可以根据需要调整
- On Error GoTo 0
-
- If IsError(monthStart) Then
- MsgBox "请输入正确的月份格式(如:10)在A2。"
- Exit Sub
- End If
-
- ' 计算该月最后一天
- monthEnd = DateSerial(Year(monthStart), Month(monthStart) + 1, 0)
-
- ' 计算工作日数量
- workDayCount = 0
- currentDate = monthStart
- Do While currentDate <= monthEnd
- If Weekday(currentDate) <> vbSunday Then ' 排除周日
- workDayCount = workDayCount + 1
- End If
- currentDate = currentDate + 1
- Loop
-
- ' 检查总工时是否超出每天8小时的限制
- If totalHours > workDayCount * 8 Then
- ws.Cells(projectRow, 3).Value = "该项目总工时过长,请重新修改总工时!" ' 在C列提示错误信息
- GoTo NextProject ' 跳过当前项目,继续下一个项目
- End If
-
- ' 初始化每天的工作时间为0
- outputCol = 3 ' C列开始输出
- For currentDay = 1 To workDayCount
- ws.Cells(projectRow, outputCol).Value = 0
- outputCol = outputCol + 1
- Next currentDay
-
- ' 分配工时
- remainingHours = totalHours
- Do While remainingHours > 0
- outputCol = 3 ' 重置列位置
- For currentDay = 1 To workDayCount
- If remainingHours = 0 Then Exit For
- ' 随机生成每天的工作时间,不超过8小时
- dailyHours = Application.WorksheetFunction.Min(Int((remainingHours / (workDayCount - currentDay + 1)) * Rnd + 1), 8)
- If ws.Cells(projectRow, outputCol).Value + dailyHours <= 8 Then
- ws.Cells(projectRow, outputCol).Value = ws.Cells(projectRow, outputCol).Value + dailyHours
- remainingHours = remainingHours - dailyHours
- Else
- ' 如果超出了最大值,选择一个较小的值
- dailyHours = Application.WorksheetFunction.Min(remainingHours, 8 - ws.Cells(projectRow, outputCol).Value)
- If dailyHours > 0 Then
- ws.Cells(projectRow, outputCol).Value = ws.Cells(projectRow, outputCol).Value + dailyHours
- remainingHours = remainingHours - dailyHours
- End If
- End If
- outputCol = outputCol + 1
- Next currentDay
- Loop
- NextProject:
- Next projectRow
- End Sub
复制代码
|
评分
-
1
查看全部评分
-
|