当我删除一个范围的单元格(K2:K18)得到一个debugging消息

我坚持一个VBA代码。 我的要求是,当用户从数据validation中selectK行的选项“已辞职”时,他应该得到一条popup消息,如“请在列L2上提供DD-MM-YYYY格式的用户最后工作date”。 这里L2只是一个例子。

但是,当我通过select范围K2:K18获取消息“运行时错误13,键入不匹配”

请帮忙解决这:(

以下是我的代码。

Private Sub Worksheet_Change(ByVal Target As Range) If Intersect(Target, Range("K:K")) Is Nothing Then Exit Sub If Target.Value <> "Resigned" Then Exit Sub MsgBox "Please provide the user's Last Working Date in DD-MM-YYYY format on " & Target.Offset(0, 1).Address End Sub 

您需要检查If Target.Cells.Count <> 1并适当处理。

在你的情况下,你导致_Change事件把Target参数作为Range("K2:K18")是一个数组,因此types不匹配的错误。

这里是一个简单的例子,如果Target超过1个单元格范围,则会中止该过程:

 Private Sub Worksheet_Change(ByVal Target As Range) 'Conditions which cause the event to terminate early, avoid errors If Target.Cells.Count <> 1 Then Exit Sub If Intersect(Target, Range("K:K")) Is Nothing Then Exit Sub If Target.Value = "Resigned" Then MsgBox "Please provide the user's Last Working Date in DD-MM-YYYY format on " & Target.Offset(0, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False) Application.GoTo Target.Offset(0,1) End If End Sub 

或者,要处理多个单元格区域,可以执行如下操作:

 Private Sub Worksheet_Change(ByVal Target As Range) 'Conditions which cause the event to terminate early, avoid errors Dim rng As Range, cl As Range, msg as String Set rng = Intersect(Target, Range("K:K")) If rng Is Nothing Then Exit Sub For Each cl in rng If cl.Value = "Resigned" Then msg = msg & vbCRLF & cl.Offset(0,1).Address(False,False) End If Next If msg <> vbNullString Then MsgBox "Please provide the user's Last Working Date in DD-MM-YYYY format on " & vbCrlf & msg End If End Sub