使用 Excel 中的 VBA 检查日期是否在两个给定日期之间
Check if the day is between two given days using VBA in Excel
我在 Excel 中使用 VBA 进行编码的知识有限,运行 遇到了问题。我正在尝试编写一个代码,让它根据星期几执行某些操作。
我将星期几提取为字符串,然后使用 IF...ELSE 位。代码附在下面:
Sub Schedule()
Dim Today As String
Today = Format(Date, "dddd")
If Today >= "Monday" And Today <= "Thursday" Then
'code to do something
ElseIf Today = "Friday" Then
'code to do something
ElseIf Today >= "Saturday" And Today <= "Sunday" Then
'code to do something
End If
End Sub
请指教。
使用WeekDay()
提取表示星期几的整数:
Dim Today As VbDayOfWeek
Today = Weekday(Date)
If Today >= vbMonday And Today <= vbThursday Then
....
您不能将比较操作数(>
或 <
)应用于字符串,因此您需要使用 .WeekDay()
函数而不是格式化为字符串。
文档如下:WeekDay请注意第二个可选参数。
代码如下:
Dim Today as Long
Today = WeekDay(Date)
If Today >= 2 And Today <= 5 Then
'do something
ElseIf Today = 6 Then
'do something
ElseIf Today = 7 Or Today = 1 Then
'do something
End If
A Select Case ...
适合这个 - 并且使用常量,而不是幻数:
Sub Schedule()
Select Case Weekday(Date)
Case vbMonday To vbThursday
' Code to do something.
Case vbFriday
' Code to do something else.
Case vbSaturday, vbSunday
' Code to do some fun.
End Select
End Sub
我在 Excel 中使用 VBA 进行编码的知识有限,运行 遇到了问题。我正在尝试编写一个代码,让它根据星期几执行某些操作。
我将星期几提取为字符串,然后使用 IF...ELSE 位。代码附在下面:
Sub Schedule()
Dim Today As String
Today = Format(Date, "dddd")
If Today >= "Monday" And Today <= "Thursday" Then
'code to do something
ElseIf Today = "Friday" Then
'code to do something
ElseIf Today >= "Saturday" And Today <= "Sunday" Then
'code to do something
End If
End Sub
请指教。
使用WeekDay()
提取表示星期几的整数:
Dim Today As VbDayOfWeek
Today = Weekday(Date)
If Today >= vbMonday And Today <= vbThursday Then
....
您不能将比较操作数(>
或 <
)应用于字符串,因此您需要使用 .WeekDay()
函数而不是格式化为字符串。
文档如下:WeekDay请注意第二个可选参数。
代码如下:
Dim Today as Long
Today = WeekDay(Date)
If Today >= 2 And Today <= 5 Then
'do something
ElseIf Today = 6 Then
'do something
ElseIf Today = 7 Or Today = 1 Then
'do something
End If
A Select Case ...
适合这个 - 并且使用常量,而不是幻数:
Sub Schedule()
Select Case Weekday(Date)
Case vbMonday To vbThursday
' Code to do something.
Case vbFriday
' Code to do something else.
Case vbSaturday, vbSunday
' Code to do some fun.
End Select
End Sub