Tutorial by Examples

Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 Sub FsoExample() Dim fso As Object ' declare variable Set fso = CreateObject("Scripting.FileSystemObject") ' Set it to be a File System Object ' now use it to check if a file exists Dim myFilePath A...
Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 Sub ReadTextFileExample() Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") Dim sourceFile As Object Dim myFilePath As String Dim myFileText As String myFilePath = &...
Sub CreateTextFileExample() Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") Dim targetFile As Object Dim myFilePath As String Dim myFileText As String myFilePath = "C:\mypath\to\myfile.txt" Set targetFile = fso.CreateT...
Const ForReading = 1 Const ForWriting = 2 Const ForAppending = 8 Sub WriteTextFileExample() Dim oFso Set oFso = CreateObject("Scripting.FileSystemObject") Dim oFile as Object Dim myFilePath as String Dim myFileText as String myFilePath = "C:\my...
Early bound (requires a reference to Microsoft Scripting Runtime): Public Sub EnumerateDirectory() Dim fso As Scripting.FileSystemObject Set fso = New Scripting.FileSystemObject Dim targetFolder As Folder Set targetFolder = fso.GetFolder("C:\") Dim foundFi...
Early Bound (with a reference to Microsoft Scripting Runtime) Sub EnumerateFilesAndFolders( _ FolderPath As String, _ Optional MaxDepth As Long = -1, _ Optional CurrentDepth As Long = 0, _ Optional Indentation As Long = 2) Dim FSO As Scripting.FileSystemObject Set ...
Dim fso As New Scripting.FileSystemObject Debug.Print fso.GetBaseName("MyFile.something.txt") Prints MyFile.something Note that the GetBaseName() method already handles multiple periods in a file name.
Dim fso As New Scripting.FileSystemObject Debug.Print fso.GetExtensionName("MyFile.something.txt") Prints txt Note that the GetExtensionName() method already handles multiple periods in a file name.
The GetParentFolderName method returns the parent folder for any path. While this can also be used with folders, it is arguably more useful for extracting the path from an absolute file path: Dim fso As New Scripting.FileSystemObject Debug.Print fso.GetParentFolderName("C:\Users\Me\My Docume...
If you're accepting user input for folder paths, you might need to check for trailing backslashes (\) before building a file path. The FSO.BuildPath method makes this simpler: Const sourceFilePath As String = "C:\Temp" '<-- Without trailing backslash Const targetFilePath As Strin...

Page 1 of 1