[英]Copy multiple sheets from one workbook to a new one, but copy values not formulas. Then save in current directory as today's date
[英]Is there a more elegant way to execute if statement only if a new date is at least one month different from the current one?
編輯:我只想執行代碼,如果新的日期是在將來和月份不同。
我有兩個約會。 我只想在新日期與舊日期不同的月份執行代碼,但是我需要執行兩種不同類型的代碼:
1.如果新日期的月份是將來的月份
例如,如果新日期是2021年1月15日,舊日期是2020年3月15日,我要執行第1部分。
2.如果新日期是過去的月份,則使用不同的代碼
例如,如果新日期是2020年3月15日,舊日期是2021年1月15日,我要執行第2部分
我認為有一種比我在代碼中做的更好的方法
Dim old_date as variant
Dim new_date as variant
**'NOTE: For the intents of this code, the new_date and old_date have been previously defined by the user in a previous part of code**
If CLng(Format(new_date, "yyyymm")) <> CLng(Format(old_date, "yyyymm")) Then
If CLng(Format(new_date, "yyyymm")) > CLng(Format(old_date, "yyyymm")) Then
'Temporary msgbox for my testing purposes
MsgBox "Your new date is in a month in the future"
'Additional code to execute
Else
'Temporary msgbox for my testing purposes
MsgBox "Your new date is in a month in the past"
'Additional code to execute
End If
End If
我的代碼按原樣工作,但我知道做事要比做事更好
第一個參數為“ m”的DateDiff
將返回一個等於月差的數字。 如果它是正數,則其正向,負數是后向,0相同。
https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/datediff-function
Dim old_date as date
Dim new_date as date
dim monthdatediff as long
monthdatediff = datediff("m", old_date, new_date)
if monthdatediff = 0 then
msgbox "Same Month"
elseif monthdatediff > 0 then
msgbox "Future Month"
else
msgbox "Past Month"
end if
嗯,是的,我最初想到的是new_date> old_date,但是如果new_date> old_date和月份不同,我只想執行代碼的第1部分(例如,如果new_date> old_date和month(new_date)<> month(old_date)) – newtovba 3分鍾前
在這種情況下,找到月份並按如下所示進行操作。
Option Explicit
Sub Sample()
Dim old_date As Date
Dim new_date As Date
Dim oldDateMonth As Long
Dim newDateMonth As Long
'~~> Populating from B2 and B3. Change as applicable
old_date = [b2]: new_date = [b3]
'~~> Get the month
oldDateMonth = Month(old_date)
newDateMonth = Month(new_date)
If new_date > old_date Then
If oldDateMonth <> newDateMonth Then
'
' Do what you want (PART 1)
'
End If
End If
End Sub
您的代碼看起來不錯。 我更喜歡使用正確的類型( Date
此處):更快,更安全。
您還可以略微簡化邏輯。
Dim old_date as Date
Dim new_date as Date
If new_date > old_date Then
debug.print now, "Your new date is in a month in the future"
'Additional code to execute
ElseIf new_date < old_date
debug.print "Your new date is in a month in the past"
'Additional code to execute
End If
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.