How do I use FileSystemObject in VBA?
In excel 2013 the object creation string is:
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
instead of the code in the answer above:
Dim fs,fname
Set fs=Server.CreateObject("Scripting.FileSystemObject")
Within Excel you need to set a reference to the VBScript run-time library.
The relevant file is usually located at \Windows\System32\scrrun.dll
- To reference this file, load the Visual Basic Editor (ALT+F11)
- Select Tools > References from the drop-down menu
- A listbox of available references will be displayed
- Tick the check-box next to '
Microsoft Scripting Runtime
' - The full name and path of the
scrrun.dll
file will be displayed below the listbox - Click on the OK button.
This can also be done directly in the code if access to the VBA object model has been enabled.
Access can be enabled by ticking the check-box Trust access to the VBA project object model
found at File > Options > Trust Center > Trust Center Settings > Macro Settings
To add a reference:
Sub Add_Reference()
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\System32\scrrun.dll"
'Add a reference
End Sub
To remove a reference:
Sub Remove_Reference()
Dim oReference As Object
Set oReference = Application.VBE.ActiveVBProject.References.Item("Scripting")
Application.VBE.ActiveVBProject.References.Remove oReference
'Remove a reference
End Sub
These guys have excellent examples of how to use the filesystem object http://www.w3schools.com/asp/asp_ref_filesystem.asp
<%
dim fs,fname
set fs=Server.CreateObject("Scripting.FileSystemObject")
set fname=fs.CreateTextFile("c:\test.txt",true)
fname.WriteLine("Hello World!")
fname.Close
set fname=nothing
set fs=nothing
%>
After adding the reference, I had to use
Dim fso As New Scripting.FileSystemObject