我在VBA进行简短的计算,计算两个时间间隔内的星期二,星期四,星期六和星期日的数量。我不断收到各种错误,但据我所知,代码是合理的。我很感激任何帮助或修改。具体来说,我认为我的DatePart()可能存在缺陷
Public Function ModWeekdays(ByRef NotificationDate As Date, ByRef OrderDate As Date, ByRef PlacementDate As Date, ByRef ReleaseDate As Date) As Integer
Dim numWeekdays As Integer
Dim totalDays As Integer
Dim totaldays2 As Integer
Dim WeekendDays As Integer
Dim WeekendDays2 As Integer
numWeekdays = 0
WeekendDays = 0
WeekendDays2 = 0
'totalDays = DateDiff(Day, NotificationDate, OrderDate) + 1
'for i as integer = 1 to totalDays
If DatePart(Day, NotificationDate) = 1 Then
WeekendDays = WeekendDays + 1
End If
If DatePart(dateinterval.Weekday, startDateNotificationDate) = 3 Then
WeekendDays = WeekendDays + 1
End If
If DatePart(dateinterval.Weekday, NotificationDate) = 5 Then
WeekendDays = WeekendDays + 1
End If
If DatePart(dateinterval.Weekday, NotificationDate) = 7 Then
WeekendDays = WeekendDays + 1
End If
NotificationDate = DateAdd("d", 1, NotificationDate)
'///////////////////////////////////////////////////////////////////////////
totaldays2 = DateDiff(dateinterval.Day, PlacementDate, ReleaseDate) + 1
If DatePart(dateinterval.Weekday, PlacementDate) = 1 Then
WeekendDays2 = WeekendDays2 + 1
End If
If DatePart(dateinterval.Weekday, PlacementDate) = 3 Then
WeekendDays2 = WeekendDays2 + 1
End If
If DatePart(dateinterval.Weekday, PlacementDate) = 5 Then
WeekendDays2 = WeekendDays2 + 1
End If
If DatePart(dateinterval.Weekday, PlacementDate) = 7 Then
WeekendDays2 = WeekendDays2 + 1
End If
PlacementDate = DateAdd("d", 1, PlacementDate)
numWeekdays = WeekendDays + WeekendDays2
Dim MyReturnVal As Integer
MyReturnVal = ModWeekdays(NotificationDate, OrderDate, PlacementDate, ReleaseDate)
End Function
答案 0 :(得分:0)
您需要阅读MS文档 -
DatePart(间隔,日期[,firstdayofweek [,firstweekofyear]])
DatePart函数语法具有以下命名参数:
间隔必需。字符串表达式,是您要返回的时间间隔。
日期必填。要评估的变量(日期)值。
firstdayofweek可选。一个常量,指定一周的第一天。如果未指定,则假定星期日。
firstweekofyear可选。一个常量,指定一年中的第一周。如果未指定,则假定第一周是1月1日发生的那一周。
设置
interval参数具有以下设置:
设置说明
yyyy Year
q Quarter
m Month
y Day of year
d Day
w Weekday
ww Week
h Hour
n Minute
s Second
第一个问题行代码更正为 -
'If DatePart(Day, NotificationDate) = 1 Then
If DatePart("w", NotificationDate) = 1 Then
同样对于剩下的,如果你想要的话,请加上“w”或“d”。
最后,检查输入参数的准确性。由于算法的递归性质,我的示例args很快产生了“内存不足”的错误。 TKX