Wednesday, April 21, 2010

Creating and Managing Folders using VB Script

We can create Folders in VB Script interacting with File System Object. So using the script we can create folder, manipulate with folders etc through VB Scripting.



Create Folder Method creates a folder in the location specified. If a folder already exists with the same name an error occurs. The CreateFolder method always returns a Folder object if it is not there. The syntax of the CreateFolder method is

object.CreateFolder(foldername)


Example 1: Write a script to print all the file names from a folder.

'Step 1: Create and object variable to interact with the File system object
Set fso=createobject("Scripting.filesystemobject")

'Step 2: Point to the folder from which we want to print
'the file names
Set fol = fso.GetFolder("F:\YouTube Downloader")

'Step 3: Return all the files collection from the specified folder
Set fil = fol.files

'Print all the file names from the specified folder
For each f in fil
str = str&" "&f.name&", "
Next

Msgbox "The file name is: "&str

If we look in the above script we look at this line str = str&" "&f.name&", "

Let me explain what actually happens. In order to print all the file names in a single message box we need to initialize a string in the loop and assign the string with str and concatenate with space and f.name (file name) and a comma so that each file will be displayed separated by a comma. What happens is that the str will start storing all the file names until the loop is terminated and this string is used in the message box to print the desired output.

For each statement is used to point to each file till it reaches the end of the file collection. Here f variable is used to point to each file in the collection.

No comments:

Post a Comment