我在Excel中创建了一个VBA宏来执行某些操作,如果单元格在给定的范围内但是当我执行它时它会给我一个错误,我不明白为什么。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim isect As Boolean
isect = Application.Intersect(Selection, Range("D11:D35"))
If isect Then
If ActiveCell.Offset(-1, 0) - ActiveCell.Offset(-1, 1) > 2.5 Then
Range("A1:A1").Value = "ok"
End If
End If
End Sub
错误是:
Object variable or With block variable not set.
答案 0 :(得分:0)
将前3行更改为:
Dim isect As Range
Set isect = Application.Intersect(Selection, Range("D11:D35"))
If Not isect Is Nothing Then
但请查看@Siddharth关于循环的评论,这在这里非常重要。
答案 1 :(得分:0)
另一种不使用Boolean Variable
/ Selection
的方法(也包含Tim的建议)......
Private Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo Whoa
Application.EnableEvents = False
If Target.Cells.CountLarge > 1 Then
MsgBox "More than 1 cell ws changed"
Else
If Not Intersect(Target, Range("D11:D35")) Is Nothing Then
If Target.Offset(-1, 0).Value - Target.Offset(-1, 1).Value > 2.5 Then
Range("A1").Value = "ok"
End If
End If
End If
Letscontinue:
Application.EnableEvents = True
Exit Sub
Whoa:
MsgBox Err.Description
Resume Letscontinue
End Sub
注意:为什么.CountLarge
?见this