[英]Using a date variable in VBA macro?
我正在嘗試在宏中使用日期變量,在這里我有一個日期作為輸入,並且我想為其計算日期。 這是一段代碼:
Dim ntf as Date
'#An example of ntf is "12/10/2006 15:17:09" (properly formatted as a date)
Sheets("myshhet").Select
ntf = Cells(2, 4)
Cells(6, 6).FormulaR1C1 = "=WEEKDAY(" & ntf & ")"
但這給我錯誤
運行時錯誤'1004'
在出現公式的行中)。
相反,如果我使用:
Dim ntf as Long
它可以工作,但是給出錯誤的結果。
我究竟做錯了什么?
要使用日期,請將日期字符串放在引號中。
Dim ntf As Date
'# An example of ntf is ntf = 12/10/2006 15:17:09 (properly formatted as a date
ntf = Sheets("sheet5").Cells(2, 4).Value
Sheets("sheet5").Cells(6, 6).Formula = "=WEEKDAY(""" & ntf & """)"
或者對於Long,您需要使用Integer部分,而不要讓vba將數字四舍五入。 日期時間是十進制。 因此,只要您的時間大於中午,它將四舍五入到第二天。 您需要強迫它不要四舍五入。
Dim ntf As Long
'# An example of ntf is ntf = 12/10/2006 15:17:09 (properly formatted as a date
ntf = Int(Sheets("sheet5").Cells(2, 4).Value2)
Sheets("sheet5").Cells(6, 6).Formula = "=WEEKDAY(" & ntf & ")"
或者避免所有這些,而改為使用double:
Dim ntf As Double
'# An example of ntf is ntf = 12/10/2006 15:17:09 (properly formatted as a date
ntf = Sheets("sheet5").Cells(2, 4).Value2
Sheets("sheet5").Cells(6, 6).Formula = "=WEEKDAY(" & ntf & ")"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.