2015-08-20 160 views
3

在我的表格列B:C中允许日期。我试图创建一个检查,看看在C中输入的日期是否比B更新,如果这么好,还会提醒用户并清除内容。 我的代码返回运行时错误91在application.intersect行:Excel VBA在比较日期的两个单元格时出错

Private Sub Worksheet_Change(ByVal Target As Range) 

    Dim Dates As Range 
    Set Dates = Range("C4:C12") 

    If Target.Cells.Count > 1 Or IsEmpty(Target) Then 
    Exit Sub 
    End If 
    If Not Application.Intersect(Dates, Range(Target.Address)).Value > ActiveCell.Offset(0, -1).Value Then 
    GoTo DatesMissMatch 
    Else 
     Exit Sub 
    End If 

DatesMissMatch: 
    Target.ClearContents 
    ActiveCell.Value = "A2" 
    MsgBox "Please re-check dates" 
End Sub 
+0

你会得到什么错误? – MatthewD

+0

当然,对不起...如果不Application.Intersect(日期,范围(Target.Address))。值> ActiveCell.Offset(0,-1).Value然后 转到DatesMissMatch –

回答

2

我改变了你的方法,但这似乎是工作。

我还注意到您正在编写A2ActiveCell而不是Target。如果输入了无效数据,您是否希望C列中的单元格更新?或者您是否打算将它移动到更改的那个单元格中?

无论如何,这里有一个方法,我想出了它

Private Sub Worksheet_Change(ByVal Target As Range) 

     If Target.Cells.Count > 1 Or IsEmpty(Target) Then 
       Exit Sub 
     End If 

     If Target.Column = 3 Then 'Check to see if column C was modified 
       If Target.Value < Target.Offset(0, -1).Value Then 
         Target.ClearContents 
         Target.Value = "A2" 
         MsgBox "Please re-check dates" 
       End If 
     End If 

End Sub 

如果你想坚持目前你正在做的方式,那么我认为你需要检查的交集不是空作为另一个答案的结论。

+0

这个工程很神奇。非常感谢! –

+1

没问题,如果你不介意点击绿色复选标记来接受我的答案(如果这对你有用),我将不胜感激。我喜欢假的互联网点! :P – Soulfire

1

你可以只环行和比较的日期。

Dim ws As Excel.Worksheet 
Set ws = Application.ActiveSheet 

Dim lRow As Long 
lRow = 4 
Do While lRow <= ws.UsedRange.Rows.count 
    If ws.Range("C" & lRow).Value > ws.Range("B" & lRow).Value then 
     GoTo DatesMissMatch 
    End if 
lRow = lRow + 1 
Loop 
+0

谢谢MatthewD,关于输入数据列BI得到一个运行时错误424在行:Do而lRow <= ws.UsedRange.Rows.Count –

+0

作出更改。您需要添加昏暗的ws并设置ws行。所以ws会是当前的工作表。 – MatthewD

+0

像我这样的初学者,修改这段代码会让我陷入各种循环,但是我无法让它工作:)似乎我应该更好地定义工作范围以及循环何时停止。 –

1

我相信你只需要检查相交比做比较。

Sub Worksheet_Change(ByVal Target As Range) 

    Dim Dates As Range 
    Set Dates = Range("C4:C12") 

    If Target.Cells.Count > 1 Or IsEmpty(Target) Then 
    Exit Sub 
    End If 

    If Not Application.Intersect(Dates, Range(Target.Address)) Is Nothing Then 
     If Target.Value < Target.Offset(0, -1).Value Then 
      GoTo DatesMissMatch 
     Else 
      Exit Sub 
     End If 
    End If 

DatesMissMatch: 
    Target.ClearContents 
    ActiveCell.Value = "A2" 
    MsgBox "Please re-check dates" 
End Sub 
+0

我不知道为什么,但这让我陷入了一些循环。 –