Home » excel » excel – how to get msgbox when cell value varies exel vba

excel – how to get msgbox when cell value varies exel vba

Posted by: admin April 23, 2020 Leave a comment

Questions:

I have a cell “A1” which varies the integer values from “1 to 150”
suppose if “A1″cell.Value =”1” then i should get msgbox containing its A1 value as “1”.
and
if”A1″cell value = “2” then i should get msgbox containing its A1 value as “2”

similarly if A1 value is 3,4,5 and so on, then i should get respective cell value in msgbox
I wrote a code as seen below. but writing if code statement ranging from “1 to 150” is dificult task
can anybody minimise thise code adding variables to this.. thank you in advance

sub variable()    
    If Range("a1").Value = 1 Then
        MsgBox Worksheets("Sheet1").Range("A1").Value
    Else
        If Range("a1").Value = 2 Then
           MsgBox Worksheets("Sheet1").Range("A1").Value
        Else
           If Range("a1").Value = 3 Then
               MsgBox Worksheets("Sheet1").Range("A1").Value 
           End If
        End If
    End If    
End Sub
How to&Answers:

This is how to do rewrite the code with Select Case:

Sub MyVariable()

    Select Case Range("A1").Value
        Case 1 to 150:
            MsgBox Range("A1")
        Case Else:
            'nothing
    End Select

End Sub

Answer:

I can suggest you to write this code :

Private Sub Worksheet_Change(ByVal Target As Range)
    If (Target.Address = "$A$1") Then
        If (IsNumeric(Target.Value)) Then
            If (Target.Value >= 1 And Target.Value <= 150) Then
                MsgBox Target.Value
            End If
        End If
    End If
End Sub

Answer:

If you want to get message each time you enter different value in cell A1 , then please use code below.

Private Sub Worksheet_Change(ByVal Target As Range)
Dim DivRg As Range
Set DivRg = Range("A1")
Set DivRg = Application.Intersect(Target, DivRg)

If DivRg Is Nothing Then Exit Sub
MsgBox Target
Set DivRg = Nothing

End Sub

Please note you should put this code in your Worksheet module, not regular module.