Visual Basic

How To Write Visual Basic Script

To write Visual Basic Script (VBScript), create a plain text file, add VBScript statements, save it with a .vbs extension, and run it through Windows Script Host. Start with a small script that displays a message, then add variables, conditions and loops. Your Windows installation.

Which licences fit your PC setup?

Prices are an AUD snapshot, not a live quote. Confirm variant and total on the listing.

Check whether VBScript suits your task

VBScript is mainly useful for maintaining existing Windows automation and older applications. Microsoft lists it as a deprecated Windows feature, with removal planned for a future release. Check its availability on the computer where your script will run before relying on it.

For new Windows automation, consider PowerShell. If you need to understand or repair an existing .vbs file, the examples below cover the essentials without requiring an integrated development environment.

VBScript, Visual Basic .NET and VBA share familiar syntax but have different environments and capabilities. The store's Visual Basic guides cover related topics; check which language and application each example targets before copying code.

Create and run your first .vbs file

  1. Open Notepad or another plain text editor and create a new file.
  2. Enter the lines shown below, keeping each statement on its own line.
  3. Choose Save As, select All files if needed, and save the file as hello.vbs. Check that the filename has not become hello.vbs.txt.
  4. Open Command Prompt in the folder containing the file.
  5. Run cscript //nologo hello.vbs. The console should display Hello, World!

Option Explicit

Dim greeting

greeting = "Hello, World!"

WScript.Echo greeting

Option Explicit requires variables to be declared, which helps catch spelling mistakes. Dim declares greeting, the next line assigns its value, and WScript.Echo displays it.

Microsoft's cscript reference documents the console host and its options. The //nologo option hides the host banner. Running through the console makes output and error messages easier to inspect.

For a dialogue box, replace WScript.Echo greeting with MsgBox greeting. Double-clicking a .vbs file normally uses the graphical host, wscript.exe, depending on file associations. You do not need HTML script tags inside a standalone .vbs file.

Understand variables, values and comments

VBScript is not case-sensitive: greeting and Greeting refer to the same variable. Use consistent capitalisation anyway so the script is easier to read.

All VBScript variables use the Variant data type, which can hold different kinds of values. Write Dim count rather than Dim count As Integer. Assign numbers without quotation marks and text inside quotation marks:

Dim count, name, enabled

count = 3

name = "Alex"

enabled = True

WScript.Echo name & " has " & count & " tasks."

Use & to join text. Conversion functions such as CStr, CInt and CDbl help when you need a particular representation, but validate input before converting it: unsuitable text can cause a runtime error.

An apostrophe starts a comment, such as ' Explain why this check is needed. VBScript does not support /* ... */ comments. Put an apostrophe on each line of a longer comment.

Make decisions and repeat actions

Choose a branch with If

An If statement runs code when a condition is true. Add this example after the earlier assignment to count:

If count > 0 Then

WScript.Echo "Tasks remain."

Else

WScript.Echo "Nothing to process."

End If

Use ElseIf for another condition before Else. Indent the statements inside each branch in your editor to make the structure clear.

Use a loop that matches the job

A For...Next loop suits a known range. Declare i first when using Option Explicit:

Dim i

For i = 1 To 3

WScript.Echo "Item " & i

Next

This prints an item message for each value in the range. For Each...Next is useful for collections, while Do While...Loop repeats as long as a condition remains true. Make sure something inside a conditional loop can change that condition, otherwise it may never finish.

Organise reusable work into procedures

A Function returns a value by assigning to its own name. A Sub performs an action without returning a value. The following example uses both:

Function GreetingFor(person)

GreetingFor = "Hello, " & person

End Function

Sub ShowGreeting(person)

WScript.Echo GreetingFor(person)

End Sub

Call ShowGreeting("Alex")

Here the function call supplies the text for WScript.Echo. Call ShowGreeting("Alex") invokes the subroutine. You can also write ShowGreeting "Alex" without Call or parentheses. Keeping procedures small makes it easier to test one operation at a time.

Work with Windows objects carefully

Windows automation often uses objects created through CreateObject. Use Set when assigning an object reference. This example checks whether a file exists without changing it:

Dim files

Set files = CreateObject("Scripting.FileSystemObject")

WScript.Echo files.FileExists("C:\Temp\example.txt")

The result is True or False. Use explicit paths when working with files, because a relative path depends on the current working directory. Test reading and checking operations before adding code that writes, moves or deletes files.

Find errors without hiding them

Run the script with cscript and inspect the reported line and error description. Check undeclared variables, quotation marks, missing End If statements and inaccessible paths. Add temporary WScript.Echo statements to inspect values as execution progresses.

On Error Resume Next continues after a runtime error; it does not repair the problem. Use it around a specific operation only when you check Err.Number and Err.Description immediately afterwards. Handle the failure, then use On Error GoTo 0 to restore normal error reporting. Microsoft's guidance on handling errors in VBScript explains this approach.

Test normal input, empty values and unavailable resources. Keep a working copy before changing an existing automation script.

Choose the right route for desktop controls

If your goal is a desktop form, use examples for the relevant Visual Basic application framework. Guides to coding a clear button in Visual Basic and handling a checkbox in Visual Basic address form controls; their event handlers are not standalone VBScript examples.

Start by saving hello.vbs, run it from Command Prompt, then change the greeting and rerun it to confirm your edit works.

Other editions for separate workloads

Other editions for separate workloads; prices in AUD, confirm the total on the listing.

How to check this worked

  1. Open Settings, System, Activation and confirm the edition shown.
  2. Enter the key and run activation; expect a green tick within a minute.
  3. Reboot and re-check activation survives the restart.

FAQ

What else should you know before buying?

What do I need before starting?
Read the requirements and confirm the edition first; the steps assume the machine is compatible.
How do I know the licence is genuine?
Activate on Microsoft's servers and check Settings, System, Activation. A working activation is the test.
Is this a subscription?
Keys sold here are one-time lifetime licences. Microsoft 365 plans are billed by Microsoft instead.
What if the key fails?
Email hi@ms.codes with the order number and a screenshot. Replacement or refund applies within 30 days.

Check who prepared and reviewed this guide

Written by
MS.Codes editorial
Reviewed by
Support team

Last verified: (source review; see test status above).

Recent Post