自当前日期起20年的If语句

时间:2018-03-29 18:04:36

标签: excel vba date if-statement named-ranges

我想:

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年内。

1 个答案:

答案 0 :(得分:0)

考虑到发布的代码,我真的很难理解你要做什么。我无法想象它会一直到达错误之前抛出错误的行。

同样,这是一个简短的重写,我认为接近你想要做的事情。即,从列VW中的工作表中获取两个日期,并将这些日期设置为变量。然后将列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范围,但设置不正确,除了更改数字格式之外,您从未真正对其进行任何操作。

有几点指示:

  1. 如果要处理变量中的日期,则将变量声明为日期。字符串日期是魔鬼。您不能减去字符串,也不能将字符串日期与其他字符串日期进行比较,而不会将自己分成一个角落。
  2. 如果您尝试使用未声明捕获拼写错误的变量,那么在您的模块中放置Option Explicit的所有代码将导致VBE抛出错误。
  3. 不要.Select.Activate。这是针对人类的,而不是代码。唯一的例外是,如果在代码的末尾,您希望将特定工作表或单元格设置为已选中。然后一个漂亮的小Sheet1.Range("A1").Select所以你的用户设置在工作表的顶部是非常酷的。