计数的VBA代码不包括开始日期和结束日期之间的假日和周末

时间:2018-06-12 11:38:43

标签: vba excel-vba ms-access excel

我使用下面的代码来计算不包括周末的实际工作日。在访问数据库上有一个假期表,代码的编写方式是在假期时从计数中排除一天。当我运行代码时,收到错误2950:保留错误。

我没有链接访问excel的经验但我从工具>启用了引用MS访问14.0对象库

Public Function WorkingDays(StartDate As Date, EndDate As Date) As Integer
'-- Return the number of WorkingDays between StartDate and EndDate
Error GoTo err_workingDays

Dim intCount As Integer

If IsDate(StartDate) And IsDate(EndDate) Then
 If EndDate >= StartDate Then

  intCount = 0
  Do While StartDate < EndDate
     StartDate = StartDate + 1

      If Weekday(StartDate, vbMonday) <= 5 And IsNull(DLookup("[Holiday]", "tblHolidays", _
        "[HolDate] = " & Format(StartDate, "\#mm\/dd\/yyyy\#;;;\N\u\l\l"))) Then

        intCount = intCount + 1

     End If
  Loop
  WorkingDays = intCount + 1
   Else
      WorkingDays = -1  
   End If
Else
   WorkingDays = -1  
End If

 exit_workingDays:
   Exit Function

err_workingDays:
   MsgBox "Error No:    " & Err.Number & vbCr & _
   "Description: " & Err.Description
   Resume exit_workingDays

End Function

1 个答案:

答案 0 :(得分:0)

您可以添加对Access和DAO的引用:

  • Microsoft Access 16.0对象库
  • Microsoft Office 16.0 Access数据库引擎对象库

然后在您的工作簿中包含此代码:

Public Function IsLookupDate(ByVal SomeDate As Date) As Boolean

    Dim db          As DAO.Database
    Dim rs          As DAO.Recordset
    Dim rsLookup    As DAO.Recordset

    Dim Filter      As String

    Set db = DAO.Workspaces(0).OpenDatabase("d:\path\holidays.accdb")
    Set rs = db.OpenRecordset("tblHolidays", dbOpenDynaset)
    rs.FindFirst "[Date] = #" & Format(SomeDate, "yyyy\/mm\/dd") & "#"

    IsLookupDate = Not rs.NoMatch

End Function

然后,检查假期:

IsHoliday = NameOfYourWorkbook.IsLookupDate(StartDate)

当然,通过将其集成到您的循环中来加快速度。