我在尝试着:
1)以日期格式设置2变量。 2)1变量不能超过当前日期的二十年。 3)然后,这些变量设置另一个变量的单元格值,这些单元格值设置为数字格式。
该宏不起作用,我在尝试将工作表编码为工作表时遇到问题。
Sub Date_Check()
'Coding Variables
Dim WB As ThisWorkbook
Dim Test_Data As Sheet1
Dim statedate as String
statedate = Format(Date, "mm/dd/yyyy")
Dim enddate as string
enddate = Format(Date, "mm/dd/yyyy")
Dim todaydate as date
'Coverage date is enddate-statedate cell
Dim CvgDate as Range
Set CvgDate(26) = enddate.value - statedate.value
Dim jj as Integer
Dim x as boolean
x = True
'set the ranges as the last cell to contain values
With Worksheet("TestData")
.Range("V2:V"). Offset(-1,0).xldown.Value2 = startdate
.Range("W2:W").Offset(-1,0).xldown.Value2 = enddate
.Range("FutureDate").Format(Date, "yyyy") = True
' Error!
' I am getting an argument not option error when trying to set futureyear.
'Create function that will check if range is 20 years within today's date.
FutureYear = 20 < DateSerial(Year, 1)
.Range("enddate").Offset(-1, 0).Select =x
.Cell.Number = "mm/dd/yyyy"
'Create an if statement using fuction
If Range("enddate").Cell <> = FutureYear Then
MsgBox "Please check that the end reporting date is within 20 years from today's date!"
End If
'Ensure that enddate meets criteria before being put in numerical format
.Range("Cvgdate").Offset(-1,0).Select
.Selection.NumberFormat = "jj"
End With
任何建议都有帮助,但我专注于确保enddate变量在当前日期的20年内。
鉴于发布的代码,我真的很难理解你要做什么。我无法想象它会在没有错误之前完全抛出错误的那一行。
同样,这是一个简短的重写,我认为它接近你想要做的事情。即,从V
和W
列中的工作表中获取两个日期,并将这些日期设置为变量。然后将enddate
列中的W
与当前日期进行比较,如果距离现在超过20年,则抛出一个消息框。
Sub Date_Check()
Dim startdate as date
Dim enddate as date
With Worksheet("TestData")
'Set startdate and end date getting it form the last populated row in each column
startdate = .Range("V2").End(xlDown).Value
enddate = .Range("W2").End(xlDown).Value
'Check to see if enddate is more than 20 years from now (ignoring leap years)
If enddate - Date > 365*20 Then
MsgBox "Please check that the end reporting date is within 20 years from today's date!"
End If
End With
End Sub
这没有考虑你的cvgdate
范围,但是设置不正确,除了更改数字格式之外你永远不会对它做任何事情。
几个指针:
Option Explicit
这将导致你的VBE抛出错误,如果你试图使用一个未被声明捕捉拼写错误的变量发生。.Select
或.Activate
。这是针对人类的,而不是代码。唯一的例外是,如果在代码的末尾,您希望将特定工作表或单元格设置为已选中。然后一个漂亮的小Sheet1.Range("A1").Select
所以你的用户设置在工作表的顶部是非常酷。