VBA Early Binding to Late Binding - excel

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.

Related

Invalid procedure call or argument in VBA

I'm trying to convert pdfs into Excel spreadsheets. I have already added the "Microsoft Scripting Runtime" reference. Help?
Option Explicit
Sub PDF_To_Excel()
Dim setting_sh As Worksheet
Set setting_sh = ThisWorkbook.Sheets("Setting")
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
......
However I keep getting a
invalid procedure call or argument error
for Dim fso As New FileSystemObject
Help?
I always use the extended syntax:
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
It has never failed for me.

Copying all content in OLEObject including header footer with format into new Word.Document/Word.Application

Recently I manage to make an automation in VBA where the external word file in the same folder as the excel file is been opened and add new content from excel then save as the word file different name. Below the code:
Dim wordapp As Word.Application
Dim wordfile As Word.Document
Set wordapp = New Word.Application
Set wordfile = wordapp.Documents.Open(Application.ActiveWorkbook.Path & "<word file name>")
wordapp.Visible = False
<code to manipulate the word.document to insert value and graph from excel>
wordfile.SaveAs Filename:=Application.ActiveWorkbook.Path & "<new word file name>"
wordapp.Quit
Set wordapp = Nothing
Set wordfile = Nothing
The original external word file is behaving like a template with header and footer and some paragraph.
Because the nature of my project, I need to embedded the external word file into the excel thus turning the external word file into OLEObject in excel file. Even though I manage to open the OLEObject and manipulate the word.document to insert value and graph from excel and save as external word file, the closed OLEObject will also retain the insert value and graph making it not good for use as template.
I come up with this code. Basically to open the OLEObject and copy the content, then create a new word file and paste the content in it so that the OLEObject will not retain any changes:
Dim objSampleReport As OLEObject
Dim wordApp As Word.Application
Dim wordFileEmbed As Word.Document
Dim wordFileNew As Word.Document
Set objSampleReport = pgReport.OLEObjects("objSampleReport")
objSampleReport.Verb xlVerbPrimary
Set wordFileEmbed = objSampleReport.Object
Set wordApp = New Word.Application
Set wordFileNew = wordApp.Documents.Add
wordFileEmbed.Content.Copy
wordFileNew.Content.PasteAndFormat
wordFileEmbed.Application.Quit False
<code to manipulate the word.document to insert value and graph from excel using wordApp.selection>
Eventhough I manage to copy the OLEObject and retain the embedded as original intended, the new created word file dont have header footer and the format is wrong.
So I try to record the copypaste behaviour using Word Macro and this is come up:
Selection.WholeStory
Selection.Copy
Windows("Document1").Activate
Selection.PasteAndFormat (wdUseDestinationStylesRecovery)
With this new knowlegde I try to come up something similar as above. This is the code:
Dim objSampleReport As OLEObject
Dim wordAppEmbed As Word.Application
Dim wordAppNew As Word.Application
Dim wordFileEmbed As Word.Document
Dim wordFileNew As Word.Document
Set objSampleReport = pgReport.OLEObjects("objSampleReport")
objSampleReport.Verb xlVerbPrimary
Set wordAppEmbed = objSampleReport.Object.Application
Set wordAppNew = New Word.Application
Set wordFileNew = wordAppNew.Documents.Add
wordAppEmbed.Activate
wordAppEmbed.Selection.WholeStory
wordAppEmbed.Selection.Copy
wordAppNew.Activate
wordAppNew.Selection.PasteAndFormat
wordAppEmbed.Quit False
<code to manipulate the word.document to insert value and graph from excel using wordApp.selection>
But this still result in header footer not been copy paste and the format still wrong. I try to play around with .PasteAndFormat type parameter but the result are still the same.
Can someone help me with this problem? My other option is to use the template as external word file and using the first code but that require me to send excel file and word file at the same time, and human error can occur if the user only copying the excel file.
May try Something in line with following code
Sub NewTest()
Dim objSampleReport As OLEObject
Dim wordAppEmbed As Word.Application
'Dim wordAppNew As Word.Application
Dim wordFileEmbed As Word.Document
Dim wordFileNew As Word.Document
Dim pgReport As Worksheet
Set pgReport = ThisWorkbook.Sheets("Sheet1") 'Used for test purpose. May Use your choice
Set objSampleReport = pgReport.OLEObjects("Object 2") 'Used for test purpose. Use use choice
objSampleReport.Verb xlOpen
Set wordAppEmbed = objSampleReport.Object.Application
Set wordFileEmbed = wordAppEmbed.ActiveDocument
Set wordFileNew = wordAppEmbed.Documents.Add
wordFileEmbed.Content.Copy
wordFileNew.Range.Paste
wordFileEmbed.Close
' Now may Work with wordFileNew for further processing New file
End Sub
Edit As suggested by #Cindy Meister's expert opinion and valuable comment, I also feel first saving the embedded document as a new file, then open that document is far more prudent option. My last code is just an attempt to make your code work and tested on simple template only. (It may fail with complex documents). Therefore, I am posting modified code in line with #Cindy Meister's comment
Sub NewTest2()
Dim objSampleReport As OLEObject
Dim wordAppEmbed As Word.Application
Dim wordFileEmbed As Word.Document
Dim wordFileNew As Word.Document
Dim pgReport As Worksheet, Fname As String
Set pgReport = ThisWorkbook.Sheets("Sheet1") 'Modify to your choice
Fname = "C:\users\user\Desktop\Test2.docx" 'Modify to your choice
Set objSampleReport = pgReport.OLEObjects("Object 2") 'Used for test purpose. May modify to your choice
objSampleReport.Verb xlOpen
Set wordAppEmbed = objSampleReport.Object.Application
Set wordFileEmbed = wordAppEmbed.ActiveDocument
wordFileEmbed.SaveAs Fname
wordFileEmbed.Close
Set wordFileNew = wordAppEmbed.Documents.Open(Fname)
' Now may Work with wordFileNew for further processing New file
End Sub
.

Unable to work with word applications from excel

I am trying to open word document from the excel but stuck at the first line when I am using the below code. I have added reference still get the compile error user- defined type not defined.
Dim oApp As Word.Application
Dim oSec As Word.Section
Dim oDoc As Word.Document
Set AppWord = CreateObject("Word.Application")
Set oApp = New Word.Application
Set oDoc = oApp.Documents.Add
You need to add a reference in the VBA context by opening VBA (Developer Tab, Click: Visual Basic), Select your Workbook and Click from the menu: Tools, References.
In the references list find the Word Object Library and make sure it is checked before clicking OK
Now try again, and don't forget to make oApp visible! :
Sub Test()
Dim oApp As Word.Application
Dim oSec As Word.Section
Dim oDoc As Word.Document
Set AppWord = CreateObject("Word.Application")
Set oApp = New Word.Application
Set oDoc = oApp.Documents.Add
oApp.Visible = True
End Sub

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.

How do I use FileSystemObject in VBA?

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

Resources