我有以下代码:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
Test = "C10"
Test1 = "C11"
If Not Application.Intersect(Target, Range(Test1)) Is Nothing Then
If Target.Value2 = "No" Then
Range(Test).ClearContents
ElseIf Target.Value2 = "Yes" Then
Sheets("Calculator").Range(Test).Value = "Hello World"
End If
End If
Application.EnableEvents = True
End Sub
如何使用“ If”语句比较两个条件?像这样:
If Target.Value2 = "No" And Test="Apple" Then
答案 0 :(得分:0)
Target
可以是一次更改的一个或多个单元格(例如,粘贴一系列单元格时可以一次更改多个单元格)。
由于您正在检查Target
是否具有单个值,因此您似乎希望更改单个单元格,这很好-但是,在这种情况下,您就不需要{{1 }}(用于检查您的单元格是否在单元格的范围内)。
我不清楚您的意图,但这是我对您尝试做的事情的解释:
Intersect
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Test As String, Test1 As String 'declare variables
Application.EnableEvents = False
Test = "C10"
Test1 = "C11"
If Target.Address = Test1 Then 'if C11 is the cell that was changed then...
If Target = "No" Then '( if C11 = "No" then... )
Range(Test).ClearContents '( erase whatever's in cell C10 )
ElseIf Target = "Yes" Then '( otherwise, if C11 = "Yes" then... )
Range(Test) = "Hello World" '( make C10 = "Hello World". )
End If
End If ' if a cell other than C10 was changed, or C11 contains
' anything except "Yes" or "No", then do nothing.
Application.EnableEvents = True
End Sub
是可选的,也是不必要的,因为它是大多数对象的默认属性。 Value
中。 Calculator
似乎是不必要的。如果确实要检查Intersect
是否在单元格范围内(例如Target
是否在B2
内),则可以使用以下方法:
A1:C3
您可以在工作表的模块中对此子进行试验,以查看Excel如何解释更改:
If Intersect(Target,Range("A1:C3") then ...