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
 

JoeMo

MrExcel MVP
Joined
May 26, 2009
Messages
16,666
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
 

mumps

Well-known Member
Joined
Apr 11, 2012
Messages
8,529
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
 

mumps

Well-known Member
Joined
Apr 11, 2012
Messages
8,529
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
 

Forum statistics

Threads
1,082,295
Messages
5,364,359
Members
400,792
Latest member
Dxmiian

Some videos you may like

This Week's Hot Topics

  • populate from drop list with multiple tables
    Hi All, i have a drop list that displays data, what i want is when i select one of those from the list to populate text from different tables on...
  • Find list of words from sheet2 in sheet1 before a comma and extract text vba
    Hi Friends, Trying to find the solution on my task. But did not find suitable one to the need. Here is my query and sample file with details...
  • Dynamic Formula entry - VBA code sought
    Hello, really hope one of you experts can help with this - i've spent hours on this and getting no-where. .I have a set of data (more rows than...
  • Listbox Header
    Have a named range called "AccidentsHeader" Within my code I have: [CODE]Private Sub CommandButton1_Click() ListBox1.RowSource =...
  • Complex Heat Map using conditional formatting
    Good day excel world. I have a concern. Below link have a list of countries that carries each country unique data. [URL...
  • Conditional formatting
    Hi good morning, hope you can help me please, I have cells P4:P54 and if this cell is equal to 1 then i want row O to say "Fully Utilised" and to...
Top