Friday, June 5, 2026 Sign InRegister FREE My Account Help
FDN Portal
FDN » COM/DCOM » COM Automation with VBScript

COM Automation with VBScript

COM Automation with VBScript

VBScript can automate any COM object that supports IDispatch (Automation). This sample demonstrates common automation scenarios.

File System Operations

' FileSystemObject — file and folder operations
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")

' Check if a file exists
If fso.FileExists("C:\logs\app.log") Then
    WScript.Echo "Log file exists."
End If

' Read a text file
Dim ts
Set ts = fso.OpenTextFile("C:\logs\app.log", 1) ' ForReading
Do While Not ts.AtEndOfStream
    WScript.Echo ts.ReadLine
Loop
ts.Close

' Write a text file
Set ts = fso.CreateTextFile("C:\output\report.txt", True) ' Overwrite
ts.WriteLine "Report generated: " & Now()
ts.WriteLine "Total records: 42"
ts.Close

' Copy/move/delete
fso.CopyFile "C:\data\source.txt", "C:\backup\source.txt"
fso.MoveFile "C:\temp\*.csv", "C:\archive\"
fso.DeleteFile "C:\temp\*.tmp"

WScript.Shell — Run Programs and Read Registry

Dim wsh
Set wsh = CreateObject("WScript.Shell")

' Run a program
wsh.Run "notepad.exe C:\readme.txt", 1, False

' Run and wait for completion
Dim intReturn
intReturn = wsh.Run("ping 192.168.1.1 -n 4", 0, True)
WScript.Echo "Ping exit code: " & intReturn

' Read/write registry
Dim strComputerName
strComputerName = wsh.RegRead("HKLM\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName\ComputerName")
WScript.Echo "Computer: " & strComputerName

wsh.RegWrite "HKCU\Software\FlameNet\LastRun", Now(), "REG_SZ"

' Environment variables
WScript.Echo "Username: " & wsh.ExpandEnvironmentStrings("%USERNAME%")
WScript.Echo "Temp dir: " & wsh.ExpandEnvironmentStrings("%TEMP%")

Automating Microsoft Excel

Dim objExcel
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True

Dim wb
Set wb = objExcel.Workbooks.Add

Dim ws
Set ws = wb.Worksheets(1)
ws.Cells(1, 1).Value = "Name"
ws.Cells(1, 2).Value = "Score"
ws.Cells(2, 1).Value = "Alice"
ws.Cells(2, 2).Value = 95
ws.Cells(3, 1).Value = "Bob"
ws.Cells(3, 2).Value = 87

ws.Range("A1:B1").Font.Bold = True
ws.Columns("A:B").AutoFit

wb.SaveAs "C:\Reports\scores.xls"
wb.Close
objExcel.Quit
Set objExcel = Nothing
« Previous Creating COM Components in VB
More in COM/DCOM
« Back to COM/DCOM « Back to FDN
FlameNet Weekly: the best of the forum, freshest listings, top Q&A — delivered every Sunday.
13 members · 0 new today · 0 online now · 767 posts in last 24h