How to Use VBScript to Save a File
By Kevin Lee
Most programming languages include options for reading and writing data, and VBScript is no exception. If you do your own coding, or if you hire a programmer for a business project, you'll likely want to save data generated by your program to a file. For example, you may write a VBScript application that builds an inventory list. After generating data and manipulating it, the program can display the output in a message box or save it to a file. Code your VBScript app to save content to a text file by learning how to use the simple WriteLine method.
Launch Notepad and paste the following code into a new document:
dim output, fileSystemObject, filePath, dataToWrite filePath = "c:\outputFolder\outputFile.txt” dataToWrite = "This is my sample data"
Replace "c:\outputFolder\outputFile.txt” with the full path of the file you’d like to save. For instance, if you want to create a file named "products.txt" in your sales folder, set the value to “c:\sales\products.txt.”
Paste the following code below that presented in the previous step:
Set fileSystemObject = CreateObject("Scripting.FileSystemObject") Set output = filesystemObject.CreateTextFile(filePath, True) output.WriteLine(dataToWrite) output.Close
This code creates a new file system object and writes your sample data to your file.
Save the file with your VBScript code and give it a file extension of ".vbs"; for example, "mycode.vbs." Launch Windows Explorer, find that file and double-click on it. The program runs and writes, "This is my sample data" to your file.
This is a simple example that shows how to use the VBS WriteLine function to send data to a file. In practice, you’ll no doubt want to save your own data instead of writing "This is my sample data." To write multiple data items, you can call the WriteLine method as many times as needed. After writing all your data, call the output.Close method, as shown in the example.
After majoring in physics, Kevin Lee began writing professionally in 1989 when, as a software developer, he also created technical articles for the Johnson Space Center. Today this urban Texas cowboy continues to crank out high-quality software as well as non-technical articles covering a multitude of diverse topics ranging from gaming to current affairs.