我正在运行一个宏,将日期值从单元格J4带到列的最后一行,并在L4:L上放置新值,并从同一行的第J列上的值减去一年。
我这一步的代码是:
Private Sub Update_Click()
Dim inputWS1 As Worksheet
Set inputWS1 = ThisWorkbook.Sheets("Universal")
lastRowUniversal = inputWS1.Cells(Rows.Count, "A").End(xlUp).Row
inputWS1.Range("L4:L" & lastRowUniversal).Value = Evaluate("=IF(ISNUMBER(J4:J" & lastRowUniversal & "),DATE(YEAR(J4:J" & lastRowUniversal & ")-1,MONTH(J4:J" & lastRowUniversal & "),DAY(J4:J" & lastRowUniversal & ")),J4:J" & lastRowUniversal & ")")
`
宏通过L4:L的值显示“1/0/1900”。所以我知道 lastrow 变量正在运行,因为它只运行到J4结束的最后一行。
你们可以帮助我纠正这个问题吗?如果J4上的价值是02/01/2017它会在L4上显示02/01/2016吗?
谢谢!
答案 0 :(得分:3)
评估有两种形式:
ActiveSheet
的范围:可能不是您期望/想要的工作表。您应该使用工作表表单,否则可能会出现意外结果。
这对我有用:
Sub Tester()
Const dtFORM As String = "=IF(ISNUMBER(J4:J<r>),DATE(YEAR(J4:J<r>)-1," & _
"MONTH(J4:J<r>),DAY(J4:J<r>)),J4:J<r>)"
Dim inputWS1 As Worksheet, lastRowUniversal
Set inputWS1 = ThisWorkbook.Sheets("Universal")
lastRowUniversal = inputWS1.Cells(Rows.Count, "A").End(xlUp).Row
'### use the *worksheet* form of Evaluate ###
inputWS1.Range("L4:L" & lastRowUniversal).Value = _
inputWS1.Evaluate(Replace(dtFORM, "<r>", lastRowUniversal))
End Sub
答案 1 :(得分:0)
它按预期工作。
您得到1/0/1900,因为J列中的相应单元格可能为空。 试试吧......
Dim lastRowUniversal As Long
Dim inputWS1 As Worksheet
Set inputWS1 = ThisWorkbook.Sheets("Universal")
lastRowUniversal = inputWS1.Cells(Rows.Count, "A").End(xlUp).Row
inputWS1.Range("L4:L" & lastRowUniversal).Value = Evaluate("=IF(ISNUMBER(J4:J" & lastRowUniversal & "),DATE(YEAR(J4:J" & lastRowUniversal & ")-1,MONTH(J4:J" & lastRowUniversal & "),DAY(J4:J" & lastRowUniversal & ")),J4:J" & lastRowUniversal & ")")
inputWS1.Range("L4:L" & lastRowUniversal).NumberFormat = "mm/dd/yyyy;;"