HOME | ABOUT US | SERVICES | ARTICLES | TEMPLATES |JOBS

Run Excel macro from an IF formula / Calling a macro from an IF formula
 
Want top get results quickly ? Would you like us to do it for you?
GET AN EXPERT, GET RESULTS !
Call our Excel Expert Helpline and get immediate assistance
Tel. 201 203 9892 


Question
In Excel, is there any way to have, say, an IF function, call or  run a macro to perform an action?
So instead of =IF(A1>5,"Greater Than Five","Not Greater Than Five"), something like =IF(A1=2,myMacro,"") will fire and execute the macro.
 
Answer
There is an indirect way in Excel to have an IF function in an Excel cell invoke a macro, here is an example with a sample formula and VBA code.

Example.
1. Open a Excel and in a worksheet cell A2   enter the formula   =IF(A1>5,myMacro,"")

2. Now place the following code snippet in the VBE environment of the same worksheet

Private Sub Worksheet_Calculate()
    myMacro
End Sub




  

Public Sub myMacro()

      
 MsgBox "Value entered in cell A1 is: " & Range("A1").Value   'Get message box confirmation that macro had been called

        If Range("A1").Value > 5 Then

                Range("A3") = "A1 is greater than 5"

        Else

                Range("A3") = "A1 is NOT greater than 5"

        End If

End Sub     
      
 
 

3. You can now experiment entering various values in cell A1, and of course modify the code in myMacro sub !

Hit Counter