Microsoft Excel中的日期比较

时间:2012-08-21 01:13:09

标签: excel vba

我有一张表(2003年和2007年),其中我有两列{Date}以{/ 1}}和FromDate类型的DateTime,格式为mm / dd / yyyy。

excel表格中可以有“n”个记录。

我想应用验证,以便在保存文件时,ToDate列的值应始终大于ToDate列的值。如果不是这种情况,则应提示错误消息

1 个答案:

答案 0 :(得分:1)

编辑: @brettdj提出了一个很好的观点 - 可能就是这种情况已经存在。如果是这样,以下内容将显示包含每个错误的消息(如果有多个错误将会非常烦人)以及debug.print它。请注意,此处的设置与下面的屏幕截图相同。这需要进入VBA编辑器中的ThisWorkbook,并将代码放入BeforeSave事件中(这只是显示错误,然后继续保存提示):

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

Dim FromDate As Range
' Note that this assumes that the ToDate column has all values
' filled out. Otherwise it will stop short.
Set FromDate = Range("B2:B" & Range("A2").End(xlDown).Row)

' Iterate each cell, checking the value next to it and showing
' an error if the ToDate is > FromDate (ignore blank FromDates)
ErrorCount = 0
For Each Cell In FromDate
  If Cell.Value < Cell.Offset(0, -1) And Cell.Value <> "" Then
    ' Handle your error however you want - this just prints
    MsgBox "Error in row " & Cell.Row
    Debug.Print Cell.Row
    ErrorCount = ErrorCount + 1
  End If
Next Cell

' If we found any errors, cancel the save event
If ErrorCount > 0 Then
  Cancel = True
End If

End Sub

如果您要输入数据......

您是否要求它使用VBA?我只是问,因为你可以在没有VBA的情况下使用数据验证来做到这一点:

1。)设置数据,选择ToDate列(不包括列标题)并单击功能区上的Data->Data Validation(我正在使用Excel 2007),更改{ {1}}下拉到Allow,将Date字段更改为Data,然后为greater than or equal to字段输入=A2

enter image description here

现在在列Start Date中输入一些值,包括那些不正确的值(这包括任何非日期[由单元格格式定义的日期,在我的情况下为B ]以及mm/dd/yyyy之前的那个。您将收到一条错误消息(如果需要,您也可以调整)。如果你确实需要/喜欢使用VBA,很高兴修改答案。

enter image description here