[英]How can I use the WEEKNUM function in a statement in VBA?
我想寫一個VBA,檢查WEEKNUM或ISOWEEKNUM是否等於該值,然后運行其余的宏。 我試過這樣做但是因為使用TODAY作為arg我得到了一個錯誤。
使用WorksheetFunction對象或Excel Application對象將本機函數調用到VBA中。
debug.print WorksheetFunction.WeekNum(Date)
debug.print application.WeekNum(Date)
debug.print WorksheetFunction.IsoWeekNum(Date)
debug.print application.IsoWeekNum(Date)
if application.WeekNum(Date) = 28 then
'it is currently 28
end if
在VBA中, TODAY()
函數由Date
替換。
WEEKNUM函數將包含1月1日的一周視為一年中的第一周。 但是,有一個歐洲標准將第一周定義為在新的一年中大部分時間(四個或更多)下降的那個星期。 這意味着,在1月的第一周中有三天或更少的年份,WEEKNUM函數返回根據歐洲標准不正確的周數。
Sub test()
Dim wn As Integer
wn = Format(Date, "ww")
Debug.Print wn
End Sub
ISO Weeknum UDF是。
ISO周數
一年中第一周的ISO標准: - 一周從星期一開始; 所以星期一是任何一周的第一天 - 一年中的第一周必須包含該年至少4天
一年中的第一個星期四總是在第1周
Public Function ISOweeknum(ByVal v_Date As Date) As Integer ISOweeknum = DatePart("ww", v_Date - Weekday(v_Date, 2) + 4, 2, 2) End Function
要測試此功能,可以添加另一個小例程。
Sub test_today_weeknum() Dim dt As Date Dim wno As Integer 'In this example, the variable called LDate would now contain the current system date. dt = Date Debug.Print dt wno = ISOweeknum(dt) Debug.Print wno End Sub
對於今天即9-7-2016,第一個給出第28周,而ISO周期函數給出27
對於9-7-2015,上述例程都將給出第28周
要在Excel中的單元格公式中獲取當前日期(沒有時間部分),請使用:
=TODAY()
但是,在VBA編程環境中,函數將是DATE()
。 Now
包含當前日期和時間,而Date
和Time
是Date
和Time
的單獨命令。這取決於您需要哪些信息。
這是在VBA中同時使用WEEKNUM()
和TODAY()
一種方法:
Sub dural()
If Evaluate("=weeknum(today())") = 28 Then
MsgBox 28
Else
MsgBox "not 28"
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.