VBA实现Excel工作日时段填充:日期分列显示及代码问题修正
修正后的Excel VBA工作日日程生成代码
原代码问题分析
- 变量名拼写不一致:混用
dtDate和datDate,导致日期更新逻辑混乱 - 行号未累计:内层循环
i每次从1开始执行,导致每次都会覆盖表格开头的单元格 - 未过滤非工作日:直接按日期循环会包含周六、周日,不符合需求
- 每日时段结束后的日期跳转逻辑错误:未正确切换到下一个工作日的起始时间
修正后的完整代码
Sub GenerateWorkdaySchedule() Dim dtIncrT As Integer Dim intCellCnt As Integer Dim currentDateTime As Date Dim endDate As Date Dim currentRow As Integer Dim nextWorkdayStart As Date ' 初始化参数 dtIncrT = 15 ' 时间间隔(分钟) intCellCnt = 780 / dtIncrT ' 每日时段行数:13小时*60分钟=780分钟,每15分钟一行 currentDateTime = CDate("2025/7/1 08:00:00") ' 起始日期时间 endDate = CDate("2025/7/5") ' 结束日期(仅日期部分,判断是否超出范围) currentRow = 1 ' 初始写入行号 ' 循环处理每个工作日 Do While DateValue(currentDateTime) <= endDate ' 判断当前日期是否为工作日(周一到周五:Weekday返回2-6) If Weekday(currentDateTime, vbMonday) <= 5 Then ' 生成当日所有时段行 For i = 1 To intCellCnt ' 写入各列内容 Cells(currentRow, 1) = Format(currentDateTime, "yyyy") Cells(currentRow, 2) = Format(currentDateTime, "MMMM") Cells(currentRow, 3) = Format(currentDateTime, "dddd d MMMM yyyy") Cells(currentRow, 5) = Format(currentDateTime, "hh:mm") ' 更新到下一个时段 currentDateTime = DateAdd("n", dtIncrT, currentDateTime) ' 行号+1 currentRow = currentRow + 1 Next i End If ' 跳转到下一天的8:00 nextWorkdayStart = DateAdd("d", 1, DateValue(currentDateTime)) & " 08:00:00" currentDateTime = CDate(nextWorkdayStart) Loop End Sub
代码修正说明
- 统一变量命名:使用
currentDateTime跟踪当前要写入的日期时间,避免拼写错误 - 新增
currentRow变量:持续累计当前写入的行号,确保每日时段写完后自动跳到下一行开始 - 加入工作日判断:通过
Weekday(currentDateTime, vbMonday) <=5筛选周一到周五的日期 - 优化日期跳转逻辑:每日时段生成完成后,自动跳转到下一天的8:00,直到超过设定的结束日期
- 调整结束日期判断:仅比较日期部分,避免因时间部分导致提前终止循环
内容的提问来源于stack exchange,提问作者Gyzmo
相关产品推荐
相关产品推荐

