How do I use FileSystemObject in VBA? - excel

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.

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

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")

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

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

Related

VBA Early Binding to Late Binding

I use this code to convert PDF Files to Excel.
Private Sub CommandButton2_Click()
Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("Tabelle1")
Dim pdf_path As String
Dim excel_path As String
pdf_path = setting_sh.Range("E11").Value
excel_path = setting_sh.Range("E12").Value
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
Set fo = fso.GetFolder(pdf_path)
Dim wa As Object
Dim doc As Object
Dim wr As Object
Set wa = CreateObject("word.application")
'Dim wa As New Word.Application
wa.Visible = True
'Dim doc As Word.Document
Dim nwb As Workbook
Dim nsh As Worksheet
'Dim wr As Word.Range
For Each f In fo.Files
Set doc = wa.documents.Open(f.Path, False, Format:="PDF Files")
Set wr = doc.Paragraphs(1).Range
wr.WholeStory
Set nwb = Workbooks.Add
Set nsh = nwb.Sheets(1)
wr.Copy
nsh.Paste
nwb.SaveAs (excel_path & "\" & Replace(f.Name, ".pdf", ".xlsx"))
doc.Close False
nwb.Close False
Next
wa.Quit
MsgBox "Done"
End Sub
The problem is, other people also want to use this function, but they don't understand to how to add the Microsoft Scripting Runtime Reference in your VBA project. I tried to convert it to late binding, but it fails all the time. Can someone help me?
Thanks.
Change this:
Dim fso As New FileSystemObject
Dim fo As Folder
Dim f As File
to this:
Dim fso As Object
Dim fo As Object
Dim f As Object
Set fso = CreateObject("Scripting.FileSystemObject")
The next code will automatically add the necessary reference:
Sub addScrRunTimeRef()
'Add a reference to 'Microsoft Scripting Runtime':
'In case of error ('Programmatic access to Visual Basic Project not trusted'):
'Options->Trust Center->Trust Center Settings->Macro Settings->Developer Macro Settings->
' check "Trust access to the VBA project object model"
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\SysWOW64\scrrun.dll"
End Sub
The above code may fail if Trust access to the VBA project object model check box is gray out, being disabled by restricted administrative security policies. In such a case, the following solution should be recommended:
To declare and set variables in Late binding way, declare and assign the objects in the next way:
Dim fso As Object, fo as Object, f as Object
set fso =CreateObject("Scripting.FileSystemObject")
It is also good to be known that Early binding is operationally faster than Late during run-time, and the programmer may benefit of intellisense suggestions, automatic capitalization of method names etc.

Scripting FileSystemObject creates Runtime 429 error on Windows

Am I missing a reference object? Trying to retrieve a list of files in a directory and have them show in a sheet.
Also, would it be possible to get the directory location from a specific cell in the file?
Sub LoopThroughFiles()
Dim oFSO As Object
Dim oFolder As Object
Dim oFile As Object
Dim i As Integer
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder("C:\VBA Folder")
For Each oFile In oFolder.Files
Cells(i + 1, 1) = oFile.Name
i = i + 1
Next oFile
End Sub
Here:
Set oFSO = CreateObject("Scripting.FileSystemObject")
Runtime error 429 on a Windows machine.
There's little to no reason at all to late-bind the Scripting library - it's present (same identical version) on every single Windows box out there, and won't work on a Mac whether you late-bind it or not.
Tools/References, add the "Microsoft Scripting Runtime" library to your project, and then declare the actual data types for your object variables; you'll get compile-time validation and intellisense/autocompletion (good-bye error 438!) for all member calls.
Early binding is your friend. Declare As Scrpiting.FileSystemObject, and then just New up the object instead of hitting the registry to resolve the "Scripting.FileSystemObject" ProgID with CreateObject:
Set fso = New Scripting.FileSystemObject
Or have a With block whithold the object reference, and then you don't even need a local variable for it:
With New Scripting.FileSystemObject
'....
End With

How do I turn off the View | Reading pane for Outlook folder?

I have this code to create a folder in Outlook from Excel. How do I set the View | Reading pane to 'off'?
Set olFolders = olSourcefolder.Parent.Folders
olFolders.Add "Audits-Actuals"'how do i set the reading pane to off?
What you want is possible but you need to do something first
Open Outlook
Create a View (Let's call it "RPO")
Then run this code
Screenshot to create the view
Public Sub CreateAndApplyView()
Dim ol As New Outlook.Application
Dim CurrentFolder As Outlook.MAPIFolder
Dim NewFolder As Outlook.Folder
Set CurrentFolder = ol.ActiveExplorer.CurrentFolder
Set NewFolder = CurrentFolder.Folders.Add("Audits-Actuals")
'~~> What you need is from here. You need to activate the folder
'~~> before you activate the view
Set CurrentFolder = NewFolder
ol.ActiveExplorer.SelectFolder CurrentFolder
ol.ActiveExplorer.CurrentView = "RPO"
End Sub
And this is what I get after running the code.
Turning off the Preview Pane can also be done in VBA without needing to create a new view.
Sub HidePreviewPane()
Dim myOlExp As Outlook.Explorer
Set myOlExp = Application.ActiveExplorer
If myOlExp.IsPaneVisible(olPreview) = False Then
myOlExp.ShowPane olPreview, True
End If
Set myOlExp = Nothing
End Sub
https://learn.microsoft.com/en-us/office/vba/api/outlook.explorer.ispanevisible

I can't close the Excel application

I have this code I wrote in VBScript for wincc, and after running it the Excel application is still running, and the project is not working properly after this script. What can I do to close the Excel app?
Here is the script:
Dim fso
Dim rowcount
Dim ExcelObject
Dim WorkbookObject
Dim file
Dim i
Dim tg
Dim objSheet1
Dim objSheet2
'Set Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ExcelObject = CreateObject("Excel.Application")
file="C:\Parametri\Codificari.xls"
Set WorkbookObject = ExcelObject.Workbooks.Open(file)
'Set objSheet1 = WorkbookObject.Worksheets(1)
Set objSheet2 = WorkbookObject.Worksheets(2)
objSheet2.Cells(1,1)=SmartTags("locatie_defect")
If (fso.FileExists(file)) Then
'Raw numbering in Excel
rowcount = objSheet2.UsedRange.Rows.count
For i=3 To rowcount
tg="defect_"&i-2
SmartTags(tg)=objSheet2.Cells(i,2)
Next
End If
On Error Resume Next
'Save and close excel
ExcelObject.DisplayAlerts = False
ExcelObject.Workbooks.Close False
ExcelObject.Workbooks.Save
ExcelObject.Quit
On Error Resume Next
The standard way to close (sans error handling)
WorkbookObject.Save
WorkbookObject.Close False
ExcelObject.Quit
Set WorkbookObject= Nothing
Set ExcelObject = Nothing
Ensure all references are fully qualified, see here. On a quick look-over this doesnt jump out from your code.
For some reason Excel doesn't follow COM rules when used as an app object. No doubt for some compatibility reason.
It does follow COM rules as a doc object.
So Set WorkbookObject = GetObject("C:\Parametri\Codificari.xls") and now when it goes out of scope it will close as long as it's not visible. So just save it and it will close when your script ends. You probably only need half the lines you have.

Page numbers or Header Info for embedded Excel file in Word Doc?

I'm trying to search an MS Word doc for embedded Excel files and save them to a different location.
1) I want to record the page number and or section name (based on header style) the embedded file was located in the Word Doc. How can I extract this info?
2) Is there anyway to get the original filename of the embedded Excel file?
Here is the code I'm using to search for embedded files. Originally
Working off the code first presented here: Extract Embeded Excel Workseet Data
Sub TestMacro2()
Application.ScreenUpdating = False
Application.DisplayAlerts = wdAlertsNone
Dim lNumShapes As Long
Dim lShapeCnt As Long
Dim xlApp As Object
Dim wrdActDoc As Document
Dim iRow As Integer
Dim iCol As Integer
Set wrdActDoc = ActiveDocument
For lShapeCnt = 1 To wrdActDoc.InlineShapes.Count
If wrdActDoc.InlineShapes(lShapeCnt).Type = wdInlineShapeEmbeddedOLEObject Then
If wrdActDoc.InlineShapes(lShapeCnt).OLEFormat.ProgID = "Excel.Sheet.8" Then
wrdActDoc.InlineShapes(lShapeCnt).OLEFormat.Edit
Set xlApp = GetObject(, "Excel.Application")
cpath = "location of interest"
xlApp.Workbooks(1).SaveAs cpath & " " & lShapeCnt
xlApp.Workbooks(1).Close
xlApp.Quit
Set xlApp = Nothing
End If
End If
Next lShapeCnt
End Sub
Note: Your code would be more efficient (and easier to read) if you assign an object that's re-used to a variable:
Dim ils as Word.InlineShape
Set ils = wrdActDoc.InlineShapes(lShapeCnt)
(1) The Range.Information method can return the page number. Something like:
Dim pageNumber as Long
pageNumber = ils.Range.Information(wdwdActiveEndPageNumber)
The other option is not as straight forward... I expect you really mean Heading style, not Header style. There is a built-in bookmark that will get the Heading preceding the current selection. That would be something like:
Dim secName as String
ils.Range.Select
secName = ActiveDocument.Bookmarks("\HeadingLevel").Range.Text
(2) If the file is not linked then your chances are slim. There's nothing VBA can get at directly, that's certain. Possibly, something might be stored in the WordOpenXML. You can check that by downloading the Open XML SDK Productivity Tool, opening such a document in it and inspecting that part of the Open XML. If it's in there then you can get at it in VBA using ils.Range.WordOpenXML to get the Open XML for the InlineShape, then parse that.

Resources