0

如果单元格在给定范围内,我在 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.
4

2 回答 2

0

将前 3 行更改为:

Dim isect As Range
Set isect = Application.Intersect(Selection, Range("D11:D35"))
If Not isect Is Nothing Then

但还要检查@Siddharth 关于循环的评论,这在这里非常重要。

于 2013-04-03T21:42:24.237 回答
0

另一种不使用Boolean Variable/的方法Selection(也包含蒂姆的建议)......

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?看到这个

于 2013-04-03T22:06:10.173 回答