具有最小值和最大值的 Excel VBA yearfrac

Excel VBA yearfrac with mins and maxes

我试图在 Excel VBA 中查找两个日期之间的周数(中间有一些最小/最大功能),出现以下类型不匹配错误(运行时错误 \\'13\\')行:

1
2
3
4
WeeksWorked = Application.WorksheetFunction.RoundDown _
             (52 * Application.WorksheetFunction.YearFrac _
             (Application.WorksheetFunction.Max(DOH, DateValue("Jan 1, 2012")), _
              DateValue("Dec 31, 2012")), 0)

任何人对我做错的事情有任何指导,将不胜感激!


不确定为什么需要在 VBA 中使用它,您可以尝试以下方法。

在 Excel 中:

假设开始日期在 A1,结束日期在 A2,然后是 A3,

1
=(NETWORKINGDAYS(A1,A2))/5

现在是从工作日的angular来看,因此每周有 5 天。如果您需要每周 7 天和正常的日子,

1
=WEEKNUM(A3)-WEEKNUM(A2)

The function WEEKNUM() in the Analysis Toolpack addin calculates the correct week number for a given date, if you are in the U.S. The user defined function below will calculate the correct week number depending on the national language settings on your computer.

如果你仍然需要使用 VBA,试试这个:(正如 Tim 指出的那样,DateDiff 非常方便。)或者你甚至可以使用 Evaluate to trigger WEEKNUM.

1
2
3
4
5
Option Explicit

Function numWeeks(startDate As Date, endDate As Date)
    numWeeks = DateDiff("ww", startDate, endDate)
End Function

在 WEEKNUM 上使用评估:

1
2
3
4
5
6
Function numWeeks(startDate As Range, endDate As Range)
Dim s As Integer, t As Integer
    s = Application.Evaluate("=WEEKNUM(" & startDate.Address &",1)")
    t = Application.Evaluate("=WEEKNUM(" & endDate.Address &",1)")
    numWeeks = t - s
End Function
  • Excel VBA DataTime 函数参考


enter image description here试试下面的代码:

1
2
3
4
5
6
7
8
9
10
11
12
Sub example()

Dim dob As Date
dob = #7/31/1986#

Dim todaydt As Date
todaydt = Date

Dim numWeek As Long
numWeek = DateDiff("ww", dob, todaydt) ' Difference in weeks

End Sub

按照评论中的建议,您可以这样做:

1
debug.print DateDiff("ww", DateValue("Jan 1, 2012"), DateValue("Dec 31, 2012"))

如果出于某种原因您想自己滚动,您可以截断以下商:

1
2
3
| day1 - day2 |
---------------
       7

示例代码:

1
2
3
4
5
6
7
8
9
10
Sub test_numWeeks_fn()
    Call numWeeks(DateValue("Jan 1, 2012"), DateValue("Dec 31, 2012"))
End Sub

Function numWeeks(d1 As Date, d2 As Date)
    Dim numDays As Long
    numDays = Abs(d1 - d2)
    numWeeks = Int(numDays / 7)
    Debug.Print numWeeks
End Function

结果:

1
52