excel methods reference - How do I use FileSystemObject in VBA?
Within Excel you need to set a reference to the VB script run-time library.
The relevant file is usually located at
- 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.dllfile will be displayed below the listbox
- Click on the OK button.
Is there something that I need to reference? How do I use this:
Dim fso As New FileSystemObject Dim fld As Folder Dim ts As TextStream
I am getting an error because it does not recognize these objects.
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")
After importing the scripting runtime as described above you have to make some slighty modification to get it working in Excel 2010 (my version). Into the following code I've also add the code used to the user to pick a file.
Dim intChoice As Integer Dim strPath As String ' Select one file Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False ' Show the selection window intChoice = Application.FileDialog(msoFileDialogOpen).Show ' Get back the user option If intChoice <> 0 Then strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1) Else Exit Sub End If Dim FSO As New Scripting.FileSystemObject Dim fsoStream As Scripting.TextStream Dim strLine As String Set fsoStream = FSO.OpenTextFile(strPath) Do Until fsoStream.AtEndOfStream = True strLine = fsoStream.ReadLine ' ... do your work ... Loop fsoStream.Close Set FSO = Nothing
Hope it help!