目录

Excel中使用VBA自动生成排班表

Excel中使用VBA自动生成排班表

1. 背景

在我们排班过程中,会有很多的问题,比如我们的有多少个人,从什么时候开始排班,节假日是否要进行排班等等一系列问题,手动排班的话会有很多的这样那样的问题,那我们为什么不能直接使用VBA代码进行排班呢,所以我们本篇文章就是基于这样的目的来展开的。

2. 代码

以下就是我们的自动排班的代码了,让我们来使用一下吧

Sub GenerateSchedule()
    Dim startDate As Date
    Dim numPeople As Integer
    Dim peopleNames() As String
    Dim includeHolidays As Boolean
    Dim includeWeekends As Boolean
    
    ' 1. 自定义起始排班日期
    startDate = InputBox("请输入起始排班日期(格式:yyyy-mm-dd):")
    
    ' 2. 自定义排班人员数量和姓名
    numPeople = InputBox("请输入排班人员数量:")
    ReDim peopleNames(1 To numPeople)
    
    For i = 1 To numPeople
        peopleNames(i) = InputBox("请输入第 " & i & " 个人员的姓名:")
    Next i
    
    ' 3. 自定义选择是否要在节假日排班
    includeHolidays = MsgBox("是否包括节假日在内?选择是(是)或否(否)。", vbYesNo) = vbYes
    
    ' 4. 自定义选择是否要在周六周日排班
    includeWeekends = MsgBox("是否包括周末在内?选择是(是)或否(否)。", vbYesNo) = vbYes
    
    ' 输出结果到工作表
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add
    
    Dim currentDate As Date
    currentDate = startDate
    
    Dim rowCounter As Integer
    rowCounter = 1
    
    Do While Month(currentDate) = Month(startDate)
        If (includeWeekends Or (Weekday(currentDate) <> 1 And Weekday(currentDate) <> 7)) And (includeHolidays Or Not (IsHoliday(currentDate))) Then
            ws.Cells(rowCounter, 1).Value = currentDate
            ws.Cells(rowCounter, 2).Value = peopleNames((rowCounter - 1) Mod numPeople + 1)
            rowCounter = rowCounter + 1
        End If
        currentDate = currentDate + 1
    Loop
    
    MsgBox "排班表生成完成!"
End Sub

Function IsHoliday(dt As Date) As Boolean
    ' 在这里可以添加节假日判断的逻辑例如国家法定节假日等
    ' 这里简化为没有节假日的情况
    IsHoliday = False
End Function

2. 代码使用

点击开发工具,点击我们的VBA https://i-blog.csdnimg.cn/direct/00a8001dac194af2b34902ff21d86354.png

找到对应的位置,粘贴代码

https://i-blog.csdnimg.cn/direct/33b87b6900b54e1fb384bcae57e1974b.png

关闭之后,点击宏

https://i-blog.csdnimg.cn/direct/d2e97209c56946c2ad1eb544dfb71d61.png

开始执行

https://i-blog.csdnimg.cn/direct/40c310b4773f463cb64699892d2898ec.png

输入起始排班日期

https://i-blog.csdnimg.cn/direct/bc79e6dd4fbd452c837fbad0ea4be75e.png

输入排班人员数量

https://i-blog.csdnimg.cn/direct/be39b071c39a4793805d729af1f53aaa.png

输入排班人员的姓名

https://i-blog.csdnimg.cn/direct/b15738ce953841389d6f02824bb2b105.png

https://i-blog.csdnimg.cn/direct/52237945d40a4e0eb4a9a2844bea1738.png

https://i-blog.csdnimg.cn/direct/402418da7e6440e5bb79a6ee09f4977f.png

选择是否包括节假日

https://i-blog.csdnimg.cn/direct/162c3ef754e74b85889538167697dff8.png

选择是否包括周末

https://i-blog.csdnimg.cn/direct/604baa89117f4d85bab89834a066e3c0.png

完成

https://i-blog.csdnimg.cn/direct/132cf5f49d304277a12f428c1de47ace.png

我们进行简单的美化

https://i-blog.csdnimg.cn/direct/79e45ce8d0614a24b2739e6c300a542b.png

4. 其他文章

5. 更多素材

👈点击即可进行查看

如果对您有帮助,请您 点赞、收藏、关注、转发 ,让更多的人看到。

快来试试吧🥰