gpt4 book ai didi

vba - 在VBA宏中使用日期变量?

转载 作者:行者123 更新时间:2023-12-03 01:41:04 25 4
gpt4 key购买 nike

我正在尝试在宏中使用日期变量,其中我有一个日期作为输入,我想计算它的天数。这是一段代码:

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 & ")"

但它给了我错误

run-time error '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 时,您需要取整数部分,而不是让 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 & ")"

关于vba - 在VBA宏中使用日期变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48114883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com