The Ultimate VBS Tutorial

97,792

34

42

Introduction: The Ultimate VBS Tutorial

About: I find a quote from Bill Gates makes a very good description. "Be nice to nerds. Chances are you'll end up working for one."

VBS is one of the most popular programming languages on instructables so there surely will be several instructable guides on programming VBS. However, most of them rush through commands and just show the basic way to do them. They also have a lot of the same basic material. I decided to search all around instructables and w3schools.com until I had a very good list of commands. When I did I started this tutorial that really shows a lot of detail about each command. Now lets start making VBS scripts... 

You will need...

-A computer running Windows 98 or higher (No Macs)
-Notepad
-Time
-A brain

Step 1: First Things First...

Open Notepad

Start>All Programs>Accessories>Notepad

Lets get ready to script!

Step 2: Save Me!

Before we begin I should teach you how to save a vbs file in notepad.
To save a file you have to click File>Save As

Then type
name.vbs

Where it says name you can put whatever you want but it MUST end with .vbs

Step 3: Message Boxes

This makes an error message how you like it.

msgbox ("Message goes here",0+16,"Title goes here")

if the user is supposed to make a decision the variable can be added like this.

variable=msgbox ("Message goes here",0+16,"Title goes here")

The numbers in the middle vary what the messge box looks like.
Here is the list

0 - ok button only
1 - ok and cancel
2 - abort, retry and ignore
3 - yes no and cancel
4 - yes and no
5 - retry and cancel
TO CHANGE THE SYMBOL (RIGHT NUMBER)
16 - critical message icon
32 - warning icon
48 - warning message
64 - info message
DEFAULT BUTTON
0 = vbDefaultButton1 - First button is default
256 = vbDefaultButton2 - Second button is default
512 = vbDefaultButton3 - Third button is default
768 = vbDefaultButton4 - Fourth button is default
SYSTEM MODAL
4096 = System modal, alert will be on top of all aplications

Note: There are some extra numbers. You just have to add them to the numbers already there like

msgbox ("Hello World", 0+16+0+4096)

Step 4: Input Boxes

Input boxes allow the user to INPUT a text string. Here is the code for one.

variable=inputbox ("Message","Title","Default Text")

Any of the text between the commas is optional by just not putting anything there like

variable=inputbox ("Type a Message",,"Message")

Step 5: Working With Variables

Math is one of the most simple tasks for a computer. VBS can do complex math in a snap.

Vbs mainly does algebraic math but you can do other than that. First we should make a variable. That is the easiest task in the scripting world.

dim variable name here

Variables can be placed where text goes like this...

Msgbox (var)

The only rule for naming variables is no spaces allowed.
To do math, in between each part of the equation must have a space like so.

y + 5 = 6 * 8

You can also treat an equation like a variable...

Msgbox (5.5 * 3)

Note: VBS will give you an error specifically for dividing by zero so just don't do that.

Step 6: Strings

Strings are variables that hold text. You can make a string like this.

"This is a text string"

VBS will let you treat the text string as a variable but you can make a text string a variable as easy as this.

dim name

name = "This is a text string"

Note:You have to have the quotation marks or else the script will think your talking about a variable.

Note 2:Text strings do have a capacity limit to how much information they hold so be careful.

Step 7: Decisions, Decisions...

What if you needed the program to check if a variable was at a certain value? In programming that is extremely easy. The decision making command is called the IF THEN ELSE statement. An example program would be...

if 200 > 16 then
msgbox ("200 is greater than 16")
else
msgbox ("200 isn't greater than 16")
end if

That was a foolish example (since 200 will always be greater than 16) of how the if statement works. So now you see IF 200 > 16 THEN let the user know ELSE tell the user it isn't then END the IF statement.

So now you can make a program that will do one of two things. Can you do more? Yes! That is called a nested IF statement. For example...

if 200 > 16 then
msgbox ("200 is greater than 16")
else
if 200 = 16 then
msgbox ("200 is equal to 16")
else
msgbox ("200 isn't greater than 16")
end if
end if

This program will say if 200 is equal to, greater than or less than 16.

The same can be used with text strings.

if userinput = password then
msgbox ("Welcome")
else
msgbox ("Access denied")
end if

Note that 'userinput' and 'password' are variable holding text strings not text strings themselves.

Step 8: Doing the Loop

What if you want a program to repeat something forever or until something happens? Have I got a command for you! It's the do loop command! Its most basic use is this.

do
msgbox ("Hi")
loop

A more complex version would be

do until 24 > 8
msgbox ("Hi")
loop

A similar version of that code would be

do
msgbox ("Hi")
loop until 24 > 8

While the two codes look the same there is a difference. That is, the first code won't even go into the loop if the criteria is met before the loop is started while the second one has to go through the loop at least once because the 'loop until' is after everything in the loop.


Step 9: Important Command

One of the things that makes VBS special is it can work with other programs that are compatible with it by creating something called an object. In other words a VBS script can get more commands by controlling other programs. To use objects you have to let the script know what you are going to call it. Here is how you set an object...

set name = wscript.CreateObject("what the object is")

It is a good idea to set objects in the first lines of your code. There are two reasons for that.

1.It makes your program clearer to read.

2.It's impossible to use an object that hasn't been set. Its best to get that done first to avoid errors.

The next two steps will show two examples of objects.

Step 10: Shell

  Say you want your script to do something like run a program or DOS-ish commands. This object is perfect. It is called the Windows Shell object. Here is a simple way to use it to open a directory.

 set wshshell = wscript.CreateObject("wscript.shell")

wshshell.run C:\Windows

The C:\Windows folder should open.
Another command is sendkeys. It will, well, send keys, to applications. Say you want to send hello world into a program, just type.

set wshshell = wscript.CreateObject("wscript.shell")
wshshell.sendkeys "Hello World"

Another command is the Echo command which sends a message box with no picture, an OK button, and Windows Script Host in the title. An example is.

set wshshell = wscript.CreateObject("wscript.shell")
wshshell.echo "Hello World"

Step 11: Sapi

Did you ever want to make a computer talk? Sure you could open the text to speech window, but what if you want a computer to read results without any user interface?  Just use the SAPI (Speech Application Programming Interface) object.


Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "Hello world"

The speak command can also use variables.


Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak variable

Step 12: Date and Time

These commands will show the date or time if used correctly. They can be treated like variables.

--------------------(Date)-------------------------
Date (Returns system date)
Day (Returns the day (1-31)from the date command) ex. Day (Date)
Month (Returns the month (1-12) from the date command) ex. Month (Date)
Year (Returns the year from the date command) ex. Year (Date)
--------------------(Time)------------------------
Time (Returns the current system time to the second)
Second (Returns the second (0-59) from the time command) ex. Second (Time)
Minute (Returns the minute (0-59) from the time command) ex. Minute (Time)
Hour (Returns the hour (0-23) from the time command) ex. hour (Time)

For example 

msgbox (Date)
msgbox (Time)

That is a simple program that shows the use of the Date and Time commands. 

A more elaborate program that uses all of the commands listed here and some extra can be found here .

Step 13: Reading Plain Text

Say you want the computer to read from a file and store the contents as a text string. Here is a code that does just that.


Dim Textstring

Set objFSO = CreateObject("Scripting.FileSystemObject")

Set objText = objFSO.OpenTextFile("File.txt", 1)

Textstring = objText.ReadAll

Step 14: Final Exam...

This time take what you have learned from this instructable and write a program by yourself. Comment it so we all can enjoy it.

Step 15: Bye

Thank you for reading this instructable. Comment anything cool you come up with so we can all share our discoveries. 
                                                                                                                                                            -Super_Nerd-

Step 16: Additional Steps: the String Function "Replace"

mohamadelmoussa asked for a command that would replace certain words with others in text strings. The replace command is definitely, what he was looking for. Here is the basic syntax.

Replace(string,"change this to","this")

Here is an example of using the replace function...

text="This is a good instructable!"
msgbox (Replace(text,"a good","an awesome"))

Thanks for the compliment example. 

3 People Made This Project!

Recommendations

  • Leather Challenge

    Leather Challenge
  • Fruits and Veggies Speed Challenge

    Fruits and Veggies Speed Challenge
  • Tinkercad to Fusion 360 Challenge

    Tinkercad to Fusion 360 Challenge

42 Comments

0
s_kr
s_kr

2 days ago

a= MsgBox ("TEXT",4,"TITLE")
if a=6 then
a=MsgBox ("TEXT",0,"TITLE")
else
msgbox "TEXT"
end if

this?

0
thuglifefrownz
thuglifefrownz

6 years ago

How do you make a quiz, like with the input boxes and using "if then else"

0
s_kr
s_kr

Reply 2 days ago

a=inputbox ("TEXT HERE","TITLE")
if a= "ANSERW" Then
MsgBox "GOOD NEXT ONE"
else
msgbox "BAD"
end if
a=InputBox ("NEXT QUESTION TEXT","NEXT QUESTION TITLE HERE")'
if a= "ANSERW" THEN
msgbox "GOOD"
else
msgbox "BAD"
end if

yeah so here you go!

0
wilderness tech
wilderness tech

5 years ago

What is wrong with my code?

Set WshShell = WScript.CreateObject ("WScript.Shell")
WshShell.SendKeys "FirstWord"
WScript.Sleep "200"
WshShell.SendKeys "SecondWord"

0
s_kr
s_kr

Reply 2 days ago

Set objShell = WScript.CreateObject ("WScript.Shell")
objShell.Run("notepad.exe")
Wscript.sleep "2000"
objShell.SendKeys "First Word"
WScript.Sleep "2000"
objShell.SendKeys "Second Word"

it writes on your desktop you need to open a program first. Like cmd or notepad here is the fixed one, you also need to click the notepad .

0
1024bit
1024bit

Question 2 years ago

How do I open a file using a VBS Program? The command isn't working.

0
s_kr
s_kr

Answer 2 days ago

vbs script for opening files is this

x=msgbox("Your Text Here" ,0+16, "Your Title Here")
if x=1 then
Set a= CreateObject("Wscript.Shell")
objShell.Run("your program here needs to be .exe ")
end if

0
rappygames
rappygames

7 months ago

Here is mine
dim password
set wshshell = wscript.CreateObject("wscript.shell")
variable=msgbox ("You need to enter the password second time",0+16+0+4096,"Windows")
password=inputbox ("Enter Password","Windows")
if password = "password" then
msgbox ("Welcome")
else
msgbox ("Access denied")
variable=msgbox ("Logging off",64+4096,"Windows")
wshshell.run "C:\Windows\System32\shutdown.exe -L"
end if

0
Shrek6641
Shrek6641

3 years ago

How to create a password that is "kaitokid" if it is entered correctly, it will display an "allowed access" message?

0
randomguy400
randomguy400

Reply 1 year ago

variable=inputbox("box message","box title","")
if variable = "kaitokid" then
msgbox("Allowed access")
else
msgbox("Access is denied!")
end if

0
nateplayz2020
nateplayz2020

Reply 11 months ago

Actually its:
Dim pass
pass=inputbox("box message","box title","")
if pass = "kaitokid" then
msgbox("Allowed access")
else
msgbox("Access is denied!")
end if

0
Nickwow.
Nickwow.

Question 3 years ago

Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
dim variable
dim variable2
dim variable3
dim variable4
dim variable5
Sapi.speak "hello user. I am so lonely over here. do you want to continue talking to me?"
variable=MsgBox("Do you?",4+64,"Computer")
if variable = vbYes then
Sapi.speak "Ok then. I will continue"
Sapi.speak "Nick always plays games but never opens anything else"
Sapi.speak "Sorry for compaining, but I can't talk to anyone so I am depressed"
Sapi.speak "and sometimes I have some erererererererrorsss"
Sapi.speak "Am I relly a good friend?"
variable4=MsgBox("Am I relly a good friand?",4+64,"Computer")
if variable4 = vbNo then
Sap.speak "So we are not friends"
if variable5 = vbNo then
Sapi.speak "ok I will stop talking"
else
Sapi.speak "ok so we are"
else
Sapi.speak "ok so we are. I have to leave now because I have some work to do"
Sapi.speak "good bye i had a good tine talking with you"
X=MsgBox(":)")
else
Sapi.speak "don't you care about my feelings?"
variable3=MsgBox("...",4+64,"Computer")
if variable3 = vbYes then
Sapi.speak "ok"
else
variable2=MsgBox("You Will regret this",0+16,"Angry Computer")
do
Sapi.speak "error error error error"
X=MsgBox("Error",0+16,"Angry Conmputer")
loop
end if
end if
end if
end if
what is wrong over here?

0
Tortuga9207
Tortuga9207

Answer 1 year ago

well i dont know, but i hope somebody fix it becouse it looks awesome, if you have already fixed it, can you give me the code to test it?

0
nateplayz2020
nateplayz2020

Reply 11 months ago

the code is in the comment

0
nateplayz2020
nateplayz2020

11 months ago

i made a password checker
Code:
Option Explicit
Dim pass

pass = InputBox("ENter the password" , "Check Password")
if pass = "qwerty" then
msgbox ("Valid Password")
else
msgbox ("Invalid Password")
end if

0
Programer08
Programer08

3 years ago

Thanks you i create a mini-virus

variable=inputbox ("Its Virus!",Virus,"Enter Password Here!")
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "I just want to hack you WHY WHY WHY WHY WHY!"
Msgbox "Deleting System32...",0+16,"System32"
Msgbox "Deleting Complete!",2+64,"Microsoft Windows"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "HA HA HA HA HA HA HA HA HA HA"
Msgbox "Deleting usernet.exe",0+16,"This Virus"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "I delete all!"
Msgbox "Deleting all!",2+16,"Anonymous"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "I love it!"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "I HACK YOU NOW!!!!!!!!"
Msgbox "Hacking...",0+64,"Hacker"
Msgbox "Password ***** email *********** username ********"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "HA HA HA HA HA HA HA HA HA"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "Meow Meow Meow Meow!"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "Meow Meow Meow Meow!"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "Meow Meow Meow Meow!"
do
Msgbox "Meow Meow!"
Set Sapi = Wscript.CreateObject("SAPI.SpVoice")
Sapi.speak "Meow Meow Meow Meow!"
loop

0
randomguy400
randomguy400

Reply 1 year ago

I tried your code (except removed the 'do' and 'loop' bit, didn't want it constantly to meow at me haha) I gotta try this on my brother

0
mathias1234
mathias1234

Reply 1 year ago

You can pause the loop code in the task manager

0
randomguy400
randomguy400

Reply 1 year ago

Yes I know. I meant I removed the do and loop out of the code so it wouldn't repeat

0
randomguy400
randomguy400

Question 1 year ago on Step 4

OK so I created a user input box but is there any way to put the '4096' code to make the user input box show over other applications?
It works with a generic message box but not a 'User Input' box