[英]I need a VBA function to count the working days between two dates
I have this one: 我有这个:
Public Function WorkingDays(StartDate As Date, _
ByVal EndDate As Date, _
Optional ByVal Holidays As Range, _
Optional ByVal Workdays As Variant) As Long
Dim mpDays As Long
Dim mpHolidays As Variant
Dim mpWorkdays As Variant
Dim i As Long
If Not Holidays Is Nothing Then mpHolidays = Application.Transpose(Holidays)
If IsMissing(Workdays) Then
mpWorkdays = Array(2, 3, 4, 5, 6)
Else
mpWorkdays = Workdays
End If
For i = StartDate To EndDate
If Not IsError(Application.Match(Weekday(i), mpWorkdays, 0)) Then
If IsError(Application.Match(i, mpHolidays, 0)) Then
mpDays = mpDays + 1
End If
End If
Next i
WorkingDays = mpDays
End Function
but it is very slow, I use this function in my Workbook and my sheet I've 130K records. 但是它很慢,我在工作簿和我有130K记录的工作表中都使用了此功能。 How can it be improved? 如何改善?
Have you seen that Excel has the NETWORKDAYS and the WORKDAYS functions? 您是否看到Excel具有NETWORKDAYS和WORKDAYS函数?
Instead of looping through the dates from StartDate to EndDate which is very slow, why not work out the number of week days between the two dates and then loop through the holidays to see if each date falls between StartDate and EndDate? 为何不遍历从StartDate到EndDate的日期很慢,为什么不算出两个日期之间的工作日数,然后遍历假期以查看每个日期是否在StartDate和EndDate之间?
该链接具有Networkdays的公式版本(不使用实际的Networkdays函数)和VBA版本: http : //www.cpearson.com/excel/betternetworkdays.aspx
I change method to calculate work days, it's work in 00:00:32 我更改了计算工作日的方法,它在00:00:32工作
Public Function WrkDaysCount(StartDate As Date, _
ByVal endDate As Date) As Long
Dim DayStart As Long
Dim DayEnd As Long
Dim daytot As Long
Dim Nrweeks As Long
DayStart = Weekday(StartDate, vbMonday)
DayEnd = endDate - StartDate + DayStart
Nrweeks = Int(DayEnd / 7)
daytot = DayEnd - (fest * 2) - DayStart + 1
WrkDaysCount = daytot
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.