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

标签 vba excel

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

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/

相关文章:

vba - 定期删除重复的重复单元格

excel - 复制一堆工作表并使用原始工作表的范围保存?

excel - 获取 Excel 元数据

Vba: ‘On error’ 声明安全

vba - 为什么 VBA 在 ActiveWorkbook.SaveAs 上创建一个文件夹

VBA,如果跳过单元格

excel - VBA,应用程序定义或对象错误,更改透视筛选器

python - 在Python中确定Excel工作表的平均值

Excel - 禁用 F11 按键

sql - Excel 2003 如何将两张表送入数据透视表?