根据星期几自动运行宏

时间:2019-02-27 09:37:08

标签: excel vba

我正在尝试设置工作簿,该工作簿将查看星期几并提取当天的相应宏。例如,我在星期几有7个Macro的标题,因为它是星期三,所以我希望在用户打开工作簿时打开星期三宏。

我有以下代码,但不确定我要去哪里...

Private Sub Workbook_Open()

Dim sDate As String

sDate = Format(Date, "ddmmyyyy")

If Weekday(sDate, vbSunday) = 1 Then
Call SundayEfficiency
Else

If Weekday(sDate, vbMonday) = 2 Then
Call MondayEfficiency
Else

If Weekday(sDate, vbTuesday) = 3 Then
Call TuesdayEfficiency
Else

If Weekday(sDate, vbWednesday) = 4 Then
Call WednesdayEfficiency
Else

If Weekday(sDate, vbThursday) = 5 Then
Call ThursdayEfficiency
Else

If Weekday(sDate, vbFriday) = 6 Then
Call FridayEfficiency
Else

If Weekday(sDate, vbSaturday) = 7 Then
Call SaturdayEfficiency
End If

End Sub

2 个答案:

答案 0 :(得分:4)

问题在于代码的结构方式。如果我缩进您的代码,您的代码将如下所示

If Weekday(sDate, vbSunday) = 1 Then
    Call SundayEfficiency
Else
    If Weekday(sDate, vbMonday) = 2 Then
        Call MondayEfficiency
    Else
        If Weekday(sDate, vbTuesday) = 3 Then
            Call TuesdayEfficiency
        Else
            If Weekday(sDate, vbWednesday) = 4 Then
                Call WednesdayEfficiency
            Else
                If Weekday(sDate, vbThursday) = 5 Then
                    Call ThursdayEfficiency
                Else
                    If Weekday(sDate, vbFriday) = 6 Then
                        Call FridayEfficiency
                    Else
                        If Weekday(sDate, vbSaturday) = 7 Then
                            Call SaturdayEfficiency
                        End If

上面的代码将遇到的第一个问题是,您必须为每个End If添加If

您真正想要的是

If Weekday(sDate, vbSunday) = 1 Then
    Call SundayEfficiency
ElseIf Weekday(sDate, vbMonday) = 2 Then
    Call MondayEfficiency
ElseIf Weekday(sDate, vbTuesday) = 3 Then
     Call TuesdayEfficiency
ElseIf Weekday(sDate, vbWednesday) = 4 Then
   '
   '~~> And so on...
   '
End If

或者您可以使用Select Case

Select Case Weekday(Date, vbSunday)
    Case 1: SundayEfficiency
    Case 2: MondayEfficiency
    Case 3: TuesdayEfficiency
    '
    '~~> And So On
'
End Select

答案 1 :(得分:1)

如果您查看Weekday()函数的documentation,您将看到第二个参数设置将其视为一周的第一天。因此,致电Weekday(sDate, vbTuesday)将在星期二返回1,在星期三返回2,依此类推。

因此,您的代码只能在星期天正常运行。如果您将一周的第一天设置为MondayEfficiency,那么它将在星期二运行vbMonday,因为星期二是一周的第二天。如果您从星期五开始,它将在星期三运行FridayEfficiency,因为星期三是第6天。

当我们使用它时,还有其他一些可以改进的地方:Weekday()可以采用日期序列值,因此无需转换为字符串;而case语句在这里更高效,更易读。

将它们放在一起:

Private Sub Workbook_Open()

    Select Case Weekday(Date, vbSunday)
        Case 1
            Call SundayEfficiency
        Case 2
            Call MondayEfficiency
        Case 3
            Call TuesdayEfficiency
        Case 4
            Call WednesdayEfficiency
        Case 5
            Call ThursdayEfficiency
        Case 6
            Call FridayEfficiency
        Case 7
            Call SaturdayEfficiency
    End Select

End Sub