I have something like this
| A | B |
|---|---|
| Q? | Y or N |
| Number | number or zero |
What I want to do is:
If B1 = “Y” then let the user enter a number in B2. If B1 = “N”, change the value in B2 to zero and don’t allow the user to enter any number in B2 unless the user changes the value of B1 back to “Y”. Basically, the user is allowed to enter a number in B2 if and only if the B1=”Y”.
What I did so far:
- Data -> Data Validation -> Custom and here's the formula I've written
=OR(AND(B1="Y",ISNUMBER(B2)),AND(B1="N",B2=0))
This solution is not ideal b/c it does not change B2 to zero when the B1 is selected as N. Also when B1 is changed to Y, it doesn't force user to enter a new value in B2.
- I have tried to solve the problem using VBA. This is the code that I have written
ActiveSheet.Unprotect
Range("B2").Locked = False
If Target.Address = "$B$1" Then
Dim myValue As Variant
If Range("B1").Value = "N" Then
Range("B2").Value = 0
Else
myValue = InputBox("Give me some input")
Range("B2").Value = myValue
End If
End If
Range("B2").Locked = True
ActiveSheet.Protect
End Sub
This solution works fine except that I got an error when the code tries to lock B2 again to prevent users from entering numbers directly into the B2 cell (not using Inputbox). Also, I need to add some code to restrict data entry to just numbers.
Any idea how I can tackle this?
PS: I managed to resolve the above code with the help of SJR
Private Sub Worksheet_Change(ByVal Target As Range)
Worksheets("Sheet1").Unprotect
If Target.Address = "$B$1" Then
Dim myValue As Variant
If Range("B1").Value = "N" Then
Range("B2").Value = 0
Else
myValue = "no"
Do Until IsNumeric(myValue)
myValue = InputBox("Enter a number > 0")
Loop
Range("B2").Value = myValue
End If
End If
Worksheets("Sheet1").Protect
End Sub