簡體   English   中英

在VBA宏中使用日期變量?

[英]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 & ")"

問題是,在“錯誤結果”下,您可能表示它給出1而不是2或以此類推。

這是因為默認情況下,Excel中的第一天是星期日。

如果要在星期一的第一天,則將公式更改為以下內容:

Cells(6, 6).FormulaR1C1 = "=WEEKDAY(" & ntf & ",2)"

這些是返回類型:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM