0

I'm working on a basic login check in VBS on Windows, just running from a .vbs file. I’ve been trying to set a loginSuccess flag based on a username check. It prints the welcome message correctly when the name matches, but the variable loginSuccess always ends up False outside the If. I can’t tell if it’s a scoping thing or what.

Dim username
username = InputBox("Enter your name:")

If username = "admin" Then
    Dim loginSuccess
    loginSuccess = True
    MsgBox "Welcome, admin!"
Else
    loginSuccess = False
    MsgBox "Access Denied"
End If

If loginSuccess Then
    MsgBox "You're logged in"
Else
    MsgBox "Login failed"
End If

No error shows up but the last message always says "Login failed" even when I type "admin". That first MsgBox in the If block works fine so I know the condition hits.

1
  • 3
    Your code works for me. You may consider to dimension loginSuccess outside the if clause. Commented Jul 9 at 17:25

1 Answer 1

-4

It’s because you're redeclaring loginSuccess inside the If, so VBScript treats it like a new local variable there, exactly like what @Shrotter said

You could try moving the Dim loginSuccess outside the If block

It should look something like this:

Dim username
Dim loginSuccess

username = InputBox("Enter your name:")

If username = "admin" Then
    loginSuccess = True
    MsgBox "Welcome, admin!"
Else
    loginSuccess = False
    MsgBox "Access Denied"
End If

If loginSuccess Then
    MsgBox "You're logged in"
Else
    MsgBox "Login failed"
End If
Sign up to request clarification or add additional context in comments.

1 Comment

No, VBScript and VBA do not have the concept of block scoped variables, unlike VB.NET. Whatever the reason was for that code to not work, it wasn't that (and the code worked to begin with like Shrotter noted). The suggestion to move the variable declaration to the top makes the intent more clear, but does not change how this code runs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.