早上好。我肯定有人能回答我的问题。我不是很好或精通VBA所以任何和所有的帮助将不胜感激。
我有一个循环代码,当在A1和A2中输入两个日期时我运行。这给了我一年的差价。例如,我输入12/31/2021和12/31/2022,循环得到的是1/1/2022 -12/31/2022。我把这个叫做宏把所有东西移到A3。看到代码:
Sub p()
Dim FirstDate As Date
Dim LastDate As Date
Dim NextDate As Date
Dim r As Long
FirstDate = Range("A1").Value
LastDate = Range("a2").Value
r = 1
Do
FirstDate = FirstDate + 1
Cells(r, 1) = FirstDate
r = r + 1
Loop Until FirstDate = LastDate
Call Macro3
End Sub
如果有人输入一个新的日期范围,比如12/31/2022和12/31/2023分别进入A1:A2,我需要循环重新运行。
我最终将在此添加其他代码,但这是我需要开始的地方。
谢谢!
在进入循环之前验证日期是否正确。
Sub p()
Dim FirstDate As Date, LastDate As Date
Dim r As Long
FirstDate = Range("A1").Value
LastDate = Range("A2").Value
If IsDate(FirstDate) And IsDate(LastDate) Then
If Year(FirstDate) < 2021 Then
Exit Sub
ElseIf LastDate <= FirstDate Then
Exit Sub
End If
r = 1
Do
FirstDate = FirstDate + 1
Cells(r, 1) = FirstDate
r = r + 1
Loop Until FirstDate >= LastDate
Else
MsgBox "invalid dates", vbCritical
Exit Sub
End If
Call Macro3
End Sub