Your code is confusing, for a number of reasons.
Range
, when it's not qualified with a Worksheet
object, implicitly refers to the ActiveSheet
, i.e. ActiveSheet.Range
... but when it's in a worksheet's code-behind, it implicitly refers to that worksheet's Range
property, i.e. Me.Range
. Because the meaning of an unqualified Range
call depends on context, it's best to always qualify it with an explicit Worksheet
object.
So if you're in the code-behind module for Sheet1
, then Range("A1")
is equivalent to Sheet1.Range("A1")
, or even better, Me.Range("A1")
.
The two conditions will be evaluated every time, but only one of them needs to be: it's inefficient.
Truth is, you don't need to assign a Boolean
literal - a Boolean expression is much cleaner.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Me.CommandButton1.Visible = (Me.Range("A1") = 1)
End Sub
Now, assuming Application.EnableEvents
returns True
, that code will run every time the selection changes, which is rather overkill.
Handle the Worksheet.Change
event instead, and only act when the modified cell is A1
:
Private Sub Worksheet_Change(ByVal Target As Range)
If Application.Intersect(Target, Me.Range("A1")) Is Nothing And Target.Count <> 1 Then
' we don't care about that cell: bail out
Exit Sub
End If
Me.CommandButton1.Visible = (Me.Range("A1") = 1)
End Sub