
[英]Efficiently assign cell properties from an Excel Range to an array in VBA / VB.NET
[英]VB if cell is in range Excel
如果单元格在给定范围内,我在Excel中制作了一个VB makro来执行某些操作,但是当我执行它时,它给了我一个错误,我不明白为什么。
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.
将前三行更改为:
Dim isect As Range
Set isect = Application.Intersect(Selection, Range("D11:D35"))
If Not isect Is Nothing Then
但是还要检查@Siddharth关于循环的评论,这在这里非常重要。
不使用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
? 看到这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.