我正在尝试在VBA中编写一个脚本,该脚本将日期作为输入,然后知道该日期是从本周到下周一还是比它多几周。
编辑:下面的部分已经解决但是,我仍然可以使用顶部的一些帮助。我愚蠢地使用VB.Net代码而不是VBA。
我看了下面我将链接的页面似乎给了我一个方向。 Finding the date of monday in a week with VB.NET
问题是我无法使用我的VBA代码中的命令。这很奇怪,因为它似乎对其他人都有用,但VBA不会让我自己使用这些命令。有人能帮助我理解为什么吗?以下几行是我在excel VBA模块中添加代码时返回的红线。 “日期。”也没有用。
Dim today As Date = Date.Today
Dim dayIndex As Integer = today.DayOfWeek
dayIndex += 7
Dim dayDiff As Integer = dayIndex - DayOfWeek.Monday
Dim monday As Date = today.AddDays(-dayDiff)
答案 0 :(得分:1)
如果没有VBA,您可以使用公式:
=ABS(INT((WEEKDAY(A1-2)-A1+TODAY())/7))
A1是起始日期
2对应于星期一的星期几
除以7得到它的计数
您可以将Today()更改为任何日期,在这种情况下,您可以计算2个日期之间的星期一数
Sunday 1
Monday 2
Tuesday 3
Wednesday 4
Thursday 5
Friday 6
Saturday 7
您可以将公式中的2更改为1到7之间的任意数字,以对应您需要的任何周日
使用VBA
您需要UDF用户定义的函数:
Function NumbWkDays(StartDate As Date, EndDate As Date, _
Days As Long) As Integer
' Returns the number of qualifying days between (and including)
' StartDate and EndDate. Qualifying days are whole numbers where
' each digit represents a day of the week that should be counted,
' with Monday=1, Tuesday=2, etc. For example, all Mondays, Tuesdays
' and Thursdays are to be counted between the two dates, set
' WkDays = 124 on your worksheet.
'
Dim iDate As Date
Dim strQdays As String
strQdays = CStr(Days)
NumbWkDays = 0
For iDate = StartDate To EndDate
If strQdays Like "*" & CStr(Weekday(iDate, vbMonday)) & "*" Then
NumbWkDays = NumbWkDays + 1
End If
Next iDate
End Function
然后你必须将它用作公式:
=NumbWKdays(startdate,Enddate,1)
星期一1
要创建UDF,您必须: