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

问题描述 投票:0回答:1

我在尝试着:

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

excel vba date if-statement named-ranges
1个回答
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所以你的用户设置在工作表的顶部是非常酷。
© www.soinside.com 2019 - 2024. All rights reserved.