MilesToGoBeforeISleep
MilesToGoBeforeISleep

Reputation: 183

Auto MsgBox when Excel file is opened and a condition is met

I suspect this is a pretty easy answer but I'm new to VBA and trying to generate a msgbox when I open my file and a certain condition is met. My code, as it currently stands, is:

Sub StopLossWarning()

    If Range("C4").Value < 30 Then

        MsgBox "Maximum allowable loss is at " & Range("C4").Value

    End If

End Sub

The Msgbox appears fine when I run the macro. I just need it to run once automatically when I open the file.

Upvotes: 1

Views: 1902

Answers (1)

Stupid_Intern
Stupid_Intern

Reputation: 3450

Try this:

  1. Press Alt+F11 to open VBA Editor

  2. Double click on ThisWorkbook from Project Explorer

    Copy the below code and paste there.

    Private Sub Workbook_Open()
    Dim WK As Worksheet
    
    Set WK = Sheet1 'Change it to your sheet number.
    
    If WK.Range("C4").Value < 30 Then
      MsgBox "Maximum allowable loss is at " & WK.Range("C4").Value
    End If
    End Sub
    

Alternatively You can insert a new module and paste the code below there:

    Sub Auto_Open()
    Dim WK As Worksheet
    
    Set WK = Sheet1 'Change it to your sheet number.

    If WK.Range("C4").Value < 30 Then
      MsgBox "Maximum allowable loss is at " & WK.Range("C4").Value
    End If
    End Sub

Note: If you have multiple worksheet you may want to refer to ranges explicitly. Otherwise you may get undesired result

Reference

Upvotes: 1

Related Questions