[英]Excel VBA - Is there a way to get the date in the current week, given only the day name?
I need to work out a date within the current week (eg 2017/04/01) given only the day part of the date, is this possible with Excel VBA? 我只需要给出日期中的一天部分,就需要计算出当前一周内的日期(例如2017/04/01),Excel VBA是否可以? I have looked at questions like this excel vba - How to get the Day Name of Date? 我已经看过类似excel vba的问题-如何获取日期的日期名称? but they answer a different question. 但是他们回答了一个不同的问题。 I've also looked at using constants like vbTuesday but they are't helping as I still need to work out how to connect the day name to the current week. 我也看过使用vbTuesday之类的常量,但是它们没有帮助,因为我仍然需要弄清楚如何将日期名称连接到当前星期。
The main problem is turning your day name into a day number - so Tue or Tuesday returns day 1 (Monday being day 0). 主要问题是将您的日名转换为天数-因此,星期二或星期二返回第1天(星期一为第0天)。
On first thought I'd use a Select Case
statement in VBA, but there may be a better way. 最初我想在VBA中使用Select Case
语句,但是可能会有更好的方法。
The code below will calculate Mondays date ( dReturnDate
) and then add a number of days depending on what you ask for. 下面的代码将计算星期一的日期( dReturnDate
),然后根据您的要求添加天数。 A nonsensical day name will return a #Num
error. 荒谬的日期名称将返回#Num
错误。
Public Function DateFromDay(DayName As String) As Variant
Dim dReturnDate As Date
Dim lDayNumber As Long
dReturnDate = Date - Weekday(Date - 2)
Select Case DayName
Case "Mon", "Monday"
lDayNumber = 0
Case "Tue", "Tuesday"
lDayNumber = 1
Case "Wed", "Wednesday"
lDayNumber = 2
Case "Thu", "Thursday"
lDayNumber = 3
Case "Fri", "Friday"
lDayNumber = 4
Case "Sat", "Saturday"
lDayNumber = 5
Case "Sun", "Sunday"
lDayNumber = 6
Case Else
lDayNumber = -1
End Select
If lDayNumber >= 0 Then
DateFromDay = dReturnDate + lDayNumber
Else
DateFromDay = CVErr(xlErrNum)
End If
End Function
On a worksheet: 在工作表上:
=DateFromDay("Tuesday")
returns 18th April 2017 =DateFromDay("Tuesday")
返回2017年4月18日
=DateFromDay("Any Day")
returns #Num!
=DateFromDay("Any Day")
返回#Num!
A lot depends on whether you want to use vbUseSystemDayOfWeek
or if simply treating Monday as the 1st day is acceptable. 在很大程度上取决于您是否要使用vbUseSystemDayOfWeek
还是将星期一视为第一天是可以接受的。 You'd also need additional code if you wanted to accept, for example, "Mon" and "Monday" and if you wanted to protect the the lookup with UCase
. 如果要接受,例如,“ Mon”和“ Monday”,并且还想用UCase
保护查找,则还需要其他代码。
In principle, though, the function could be as simple as: 但是,原则上,该函数可以很简单:
Public Function DateFromDayName(dayName As String) As Date
Dim d As Long
d = WorksheetFunction.Match(dayName, _
Array("Monday", _
"Tuesday", _
"Wednesday", _
"Thursday", _
"Friday", _
"Saturday", _
"Sunday"), _
0)
DateFromDayName = Now - Weekday(Now, vbMonday) + d
End Function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.