VBA Beginner

RossG

New Member
Joined
Aug 21, 2019
Messages
1
I am working through EXCEL VBA Programming for Dummies from 2004. I am getting the "Compile error: Variable not defined" pop-up. Below is what my code looks like and it is verbatim as the example in the book. I know the problem has something to do with the "Option Explicit" at the top and that I need to define my variables, but I don't know how to write the code.

Option Explicit

Sub GuessName()
Msg = "Is your name" & Application.UserName & "?"
Ans = MsgBox(Msg, vbYesNo)
If Ans = vbNo Then MsgBox "Oh, never mind."
If Ans = vbYes Then MsgBox "I must be clairvoyant!"

End Sub
 

Excel Facts

How to show all formulas in Excel?
Press Ctrl+` to show all formulas. Press it again to toggle back to numbers. The grave accent is often under the tilde on US keyboards.
When you use Option Explicit you must define all variables. try
Code:
Option Explicit

Sub GuessName()
Dim Msg as String, Ans as Long
    Msg = "Is your name" & Application.UserName & "?"
    Ans = MsgBox(Msg, vbYesNo)
    If Ans = vbNo Then MsgBox "Oh, never mind."
    If Ans = vbYes Then MsgBox "I must be clairvoyant!"
    
End Sub
 
Upvote 0
Try:
Code:
Sub GuessName()
    Dim Msg As String, Ans As String
    Msg = "Is your name" & Application.UserName & "?"
    Ans = MsgBox(Msg, vbYesNo)
    If Ans = vbNo Then MsgBox "Oh, never mind."
    If Ans = vbYes Then MsgBox "I must be clairvoyant!"
End Sub
 
Upvote 0
It can actually be shortened to this:
Code:
Sub GuessName()
    If MsgBox("Is your name " & Application.UserName & "?", vbYesNo) = vbNo Then
        MsgBox "Oh, never mind."
    Else
        MsgBox "I must be clairvoyant!"
    End If
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,588
Messages
6,120,409
Members
448,959
Latest member
camelliaCase

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top