使用Excel VBA统计员工连续带薪休假时长及起止日期
实现Excel员工连续带薪休假统计的VBA方案
核心逻辑说明
- 按员工姓名分组,先对原始数据按「姓名+日期」排序,确保同员工的日期连续排列
- 遍历每个员工的休假记录,判断日期是否连续(日期差为1天)
- 记录每段连续休假的起始、结束日期,计算包含首尾日的休假天数
- 将统计结果输出到专门的汇总工作表
完整VBA代码
Sub 统计连续带薪休假() Dim wsSource As Worksheet, wsResult As Worksheet Dim lastRow As Long, i As Long, j As Long Dim empName As String, startDate As Date, endDate As Date Dim resultRow As Long ' 指定数据源工作表(替换为你的实际表名) Set wsSource = ThisWorkbook.Worksheets("原始数据") ' 创建或获取结果工作表 On Error Resume Next Set wsResult = ThisWorkbook.Worksheets("休假统计") If Err.Number <> 0 Then Set wsResult = ThisWorkbook.Worksheets.Add wsResult.Name = "休假统计" End If On Error GoTo 0 ' 初始化结果表 wsResult.Cells.Clear wsResult.Range("A1:D1") = Array("员工姓名", "连续休假起始日期", "连续休假结束日期", "休假天数") resultRow = 2 ' 获取数据源最后一行 lastRow = wsSource.Cells(Rows.Count, "B").End(xlUp).Row ' 按姓名+日期排序,确保同员工日期连续 wsSource.Range("A1:B" & lastRow).Sort Key1:=wsSource.Range("B1"), Order1:=xlAscending, _ Key2:=wsSource.Range("A1"), Order2:=xlAscending, Header:=xlYes ' 遍历统计连续休假 i = 2 ' 假设第一行是表头 Do While i <= lastRow empName = wsSource.Cells(i, "B").Value startDate = wsSource.Cells(i, "A").Value endDate = startDate ' 查找当前员工的连续日期终点 j = i + 1 Do While j <= lastRow And wsSource.Cells(j, "B").Value = empName If wsSource.Cells(j, "A").Value = endDate + 1 Then endDate = wsSource.Cells(j, "A").Value Else Exit Do End If j = j + 1 Loop ' 写入统计结果 wsResult.Cells(resultRow, "A").Value = empName wsResult.Cells(resultRow, "B").Value = startDate wsResult.Cells(resultRow, "C").Value = endDate wsResult.Cells(resultRow, "D").Value = endDate - startDate + 1 resultRow = resultRow + 1 i = j Loop ' 格式化结果表 wsResult.Range("B:C").NumberFormat = "yyyy/mm/dd" wsResult.Columns.AutoFit MsgBox "统计完成!", vbInformation End Sub
使用步骤
- 确保你的原始数据中,A列为休假日期,B列为员工姓名,第一行是表头
- 打开Excel的「开发工具」选项卡,点击「Visual Basic」进入VBA编辑器
- 插入新模块,将上述代码粘贴进去
- 替换代码中
wsSource = ThisWorkbook.Worksheets("原始数据")的表名为你的实际数据源工作表名称 - 运行宏,自动生成「休假统计」工作表,包含所需的汇总数据
内容的提问来源于stack exchange,提问作者Antonios Prappas
相关产品推荐
相关产品推荐

