我对使用“不”的目的感到困惑,也对“如果”条件的匹配感到困惑,代码说“什么都不是”,否则为“ MsgBox”运行代码

时间:2019-12-23 12:32:22

标签: excel vba

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Application.Intersect(Range("A1"), Range(Target.Address))  _
    Is Nothing Then
     MsgBox "Working"
End If

End Sub

1 个答案:

答案 0 :(得分:0)

说明在宏中

'Change-event procedure for a specific sheet
'(The code is placed in the code module of this sheet)
'Always called when something changes in the sheet that triggers the change event
Private Sub Worksheet_Change(ByVal Target As Range)
  'We need the double negation in the following line because the answer of the
  'core question "Application.Intersect(Range("A1"), Range(Target.Address))"
  'can have two different data types. An Object or the special type "Nothing"
  'if there is no object. There is no other way to ask for **no** address.
  'To ask only for an address will throw a runtime error if there is no one
  'But if it's "Not" "Nothing", then there is an address.
  'This is a bit hard to understand, but programming is like this sometimes ;-)
  If Not Application.Intersect(Range("A1"), Range(Target.Address)) Is Nothing Then
    'Message field with the text "Working" is displayed
    'when the If statement is evaluated as "true"
    MsgBox "Working"
  End If
End Sub