Issue with late binding - excel

I have a macro launched from Excel to control a Word document.
In order to prevent issues with references (Microsoft Word 15.0 Object Library or Microsoft Word 16.0 Object Library for example) I use late binding in the main macro :
Public appWord as Object
Sub MainSub()
Set appWord = GetObject(, "Word.Application")
If appWord Is Nothing Then
Set appWord = CreateObject("Word.Application")
End If
'Create temp file'
'...'
'Open temp file = strTempWordFile'
Set docWord = appWord.Documents.Open(strTempWordFile)
'Launch function to search text and remove it from the word document
SearchAndRemove rgCell2.Text, docWord
End Sub
Here is an extract of the function (in another module)
Sub SearchAndRemove(ByVal strSearchWord As String, ByRef docWord As Word.Document)
Set selWordSelection = appWord.Selection 'That works
selWordSelection.HomeKey Unit:=wdStory 'line with issue
'do the search and remove'
End Sub
If the Sub is called via declaring docWord as Word.Document (which requires reference to Microsoft Word 1X.0 Library, this line works OK :
selWordSelection.HomeKey Unit:=wdStory
If the Sub is called via declaring docWord as Object (which does not require reference to Microsoft Word 1X.0 Library, this line does not work anymore.

If you don't know the numerical equivalent then:
Open the application in question (in your case Word)
Open the VBE (Alt + F11)
Open the Immediate window (Ctrl + G)
Enter the keyword in the immediate window preceded by a ? (?wdStory)
Use the number it returns in your code.
In this case you need to replace wdStory with the number 6.
(and just read the middle line of #AlexK comment - add a reference temporarily and ?wdStory in the immediate window to see what it is)
Never thought of adding the referencing and using the immediate window in the current app. I know I'd forget to remove it again though.

Related

Open with Excel VBA a Word document, add some data and just save it (the Word document)

I'm opening a preexisting word document with Excel VBA and add some data to it and then I just want to save this file. But when I run the Excel VBA macro the word "save as" window appears.
And that's not my aim.
The word document should just be saved... (like when you add some data to the word document by hand and then press CTRL+S)
If more details are needed let me know... And many thanks for your help in advance.
Now my code:
Dim appWord As Word.Application
Dim document As Word.Document
Set appWord = CreateObject("Word.Application")
' the excel file and the word document are in the same folder
Set document = appWord.Documents.Add( _
ThisWorkbook.Path & "\Testfile.docx")
' adding the needed data to the word file
...
' in this following line of code I tried to do the correct saving... but it opens the "save as" window - I just want to save it automatically
document.Close wdSaveChanges = -1
'Close our instance of Microsoft Word
appWord.Quit
'Release the external variables from the memory
Set document = Nothing
Set appWord = Nothing
Set document = appWord.Documents.Add( _
ThisWorkbook.Path & "\Testfile.docx")
You’re not opening a document with this code, you’re creating a new, unsaved, document from an existing one. Change it to:
Set document = appWord.Documents.Open( _
ThisWorkbook.Path & "\Testfile.docx")
You’re also missing a colon.
document.Close wdSaveChanges:=-1

Compile error for Dim As Word.Range For Excel to Word Script [duplicate]

I am trying to do some relatively simple copy and pasting from Excel 2007 into Word 2007. I've looked through this site and others, and keep getting hung up on the same thing- the third line n the code below keeps giving me the "User type note defined" error msg. I am really confused since I just lifted this from another solution (and had similar issues with other solutions I tried to lift). Could someone please educate me on what is causing the error, and why?
Sub ControlWord()
' **** The line below gives me the error ****
Dim appWD As Word.Application
' Create a new instance of Word & make it visible
Set appWD = CreateObject("Word.Application.12")
appWD.Visible = True
'Find the last row with data in the spreadsheet
FinalRow = Range("A9999").End(xlUp).Row
For i = 1 To FinalRow
' Copy the current row
Worksheets("Sheet1").Rows(i).Copy
' Tell Word to create a new document
appWD.Documents.Add
' Tell Word to paste the contents of the clipboard into the new document
appWD.Selection.Paste
' Save the new document with a sequential file name
appWD.ActiveDocument.SaveAs Filename:="File" & i
' Close this new word document
appWD.ActiveDocument.Close
Next i
' Close the Word application
appWD.Quit
End Sub
This answer was mentioned in a comment by Tim Williams.
In order to solve this problem, you have to add the Word object library reference to your project.
Inside the Visual Basic Editor, select Tools then References and scroll down the list until you see Microsoft Word 12.0 Object Library. Check that box and hit Ok.
From that moment, you should have the auto complete enabled when you type Word. to confirm the reference was properly set.
As per What are the differences between using the New keyword and calling CreateObject in Excel VBA?, either
use an untyped variable:
Dim appWD as Object
appWD = CreateObject("Word.Application")
or
Add a reference to Microsoft Word <version> Object Library into the VBA project via Tools->References..., then create a typed variable and initialize it with the VBA New operator:
Dim appWD as New Word.Application
or
Dim appWD as Word.Application
<...>
Set appWd = New Word.Application
CreateObject is equivalent to New here, it only introduces code redundancy
A typed variable will give you autocomplete.

Copy Excel data to Word after Office 2016 upgrade from 2010

We copy data from Excel cells to a new Word document based on a .docx template document. The positioning in the Word document is found with a bookmark.
The VBA code has been working, but since upgrading to MS Office 2016 from 2010 we have been getting errors:
run time error 4605 this method or property is not available because
the clipboard is empty or not valid
And then I get
4605 This method or property is not available because this command is
not available for reading
I tried the wdDoc.Bookmarks… and I get
6124 You are not allowed to edit this selection because it is
protected
I checked all the protection, trust center settings, etc. and all look correct.
"editProject" is a single cell label.
Dim wdApp As Object
Dim wdDoc As Object
Set wdApp = CreateObject("Word.application")
Set wdDoc = wdApp.Documents.Open(Filename:=WdocT, ReadOnly:=True)
' Project NAME
wdDoc.Bookmarks("BOOKMARK1").Range.Select ' wdDoc.Bookmarks("CLIENT").Range.Select
xlData = Sheets("Data Input").Range("editProject") ' get the data
'THIS IS THE PROBLEM LINE
wdApp.Selection.TypeText Text:=xlData ' place in doc '8/10/19 FALLING OVER HERE
I know the doc is opening, and the bookmark is found, as I put in the following to check:
'temp TRY THIS
Dim tempRange As Word.Range
Dim tempStart As Long
Dim tempEnd As Long
' Set tempRange = wdDoc.Bookmarks("BOOKMARK1").Range
Set tempRange = wdDoc.Bookmarks("BOOKMARK2").Range ' THIS WORKS
tempStart = tempRange.Start
tempEnd = tempRange.End
I tried clearing the clipboard with the following:
' 8/10/19 Bruce the following may help with clipboard error message 4605
wdDoc.UndoClear
Dim oData As New DataObject ' object to use the clipboard
oData.SetText Text:=Empty ' clear
oData.PutInClipboard ' take in the clipboard to empty it
'Application.Wait (Now + TimeValue("00:00:10")) ' this is required to stop clipboard overflow error
Application.CutCopyMode = False ' 8/10/19 Bruce - this should clear the clipboard
DoEvents ' test fixing error 4605
' DoEvents passes control to the operating system.
' Control is returned after the operating system has
' finished processing the events in its queue
I tried the following in the appropriate place, but it makes no difference:
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
wdApp.Visible = True
I tried the following line instead of the copy, but the same error is thrown;
wdApp.Selection.MoveDown Unit:=wdLine, Count:=1
If Excel General setting "Open e-mail attachments and other uneditable files in reading view" is NOT ticked, it seems to work.
I am having a similar issue after my environment was upgraded to Office 2016. The code I had was working perfectly before the upgrade.
One thing I noticed later was that, after the upgrade to Office 2016, the same VBA code that used to work would open a Word doc in the "reading mode". In this mode, no editing of the document is allowed, no matter via the UI or via code. This is the meaning of the cryptic error message "4605 This method or property is not available because this command is not available for reading".
To get around this, I added the following line to make Word switch back to the "Print layout view".
objWord.ActiveWindow.View.Type = wdPrintView
where objWord is the Word object created by code not listed here.
Then I can use my old code like these to type text via VBA:
objWord.Selection.GoTo What:=wdGoToBookmark, Name:=bookmarkName
objWord.Selection.TypeText Text:=someText
So if you notice your VBA code happens to open a Word doc in the "Reading mode", you can try this work around.
A similar situation is described at this link and I came across it after I found my work around:
https://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/

Passing String From Excel to Word

I am trying to pass a string from Excel userform using VBA to a Word document. In the Word document I have created a field>doc variable and called it bookingRef. The code is as follows:
Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
Set doc = objWord.Documents.Open("test.docx")
objWord.ActiveDocument.variables("bookingRef").Value = Me.txtRef.Text
objWord.ActiveDocument.Fields.Update
objWord.Documents.Save
It doesn't have any errors, however when I open the document up, I have to right click and update field (I thought objWord.ActiveDocument.Fields.Update did this?). Also, it keeps locking the document so it cannot be opened again. Is there a way to unlock after save?
The document is locked because you didn't close it with the Document.Close method, so the document is still opened and therefore cannot be opened again.
Also avoid using ActiveDocument the document that was opened is set to doc
Set doc = objWord.Documents.Open("test.docx")
and can therefore be referenced with doc.
Dim objWord As New Word.Application
Dim doc As Word.Document
'Dim bkmk As Word.Bookmark
Set doc = objWord.Documents.Open("test.docx")
doc.variables("bookingRef").Value = Me.txtRef.Text
doc.Fields.Update
doc.Save
doc.Close
Also don't forget to quit your Word application after you are done.
objWord.Quit
Otherwise the instance of Word will be open until you shut down your computer.
The Fields.Update method should update the fields, but it might be unsuccessful because of an error. Check it for errors:
If doc.Fields.Update = 0 Then
MsgBox "Update Successful"
Else
MsgBox "Field " & doc.Fields.Update & " has an error"
End If
What I did (a test according comments below this answer):
(following steps according How to store and retrieve variables in Word documents)
Created a file C:\Temp\test.docx
To use the DocVariable field, follow these steps:
On the Insert menu, click Field.
In the Categories box, select Document Automation.
In the Field names list, select DocVariable.
In the New Name box, under Field properties, type the name of the document variable bookingRef.
Click OK.
Note you will see nothing in the document yet but that's ok because the variable bookingRef does not exist yet.
Save file and close Word.
Run the following code in Excel
Option Explicit
Public Sub Test()
Dim objWord As New Word.Application
On Error GoTo CLOSE_WORD_APP 'error handling to ensure there will not be any orphaned and invisible Word application left
Dim doc As Word.Document
Set doc = objWord.Documents.Open("C:\Temp\test.docx")
doc.Variables("bookingRef").Value = "This is the updated Value: " & Time
doc.Fields.Update
doc.Save
doc.Close
CLOSE_WORD_APP:
objWord.Quit SaveChanges:=False
If Err.Number <> 0 Then
Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
End If
End Sub
Open the Word document C:\Temp\test.docx and see that everything is updated:

Bad Parameters in Selection (Excel VBA)

I need to copy/paste table from Excel to owrd to a specific line. I have written the code and it works fine in the Excel and Word 2016 I used, but when I tried running in other versions (2013,2010,2007) it didn't work at all. So i try to use late binding, but it throws a Bad Parameters error in .selection
How to remove Bad Parameters? Thanks,
Here's the code :
Sub Movetable ()
'Name of the existing Word document
Const stWordDocument As String = "Test.docx"
'Word objects.
Dim wdApp As Object
Dim wdDoc As Object
Dim wdRange As Object
'Excel objects
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim xlRange As Excel.Range
'Initialize the Excel objects
Set wbBook = ThisWorkbook
Worksheets("RJ").Select
LastRow = Range("A" & Rows.Count).End(xlUp).Row
Set xlRange = Range("A4:D" & LastRow)
xlRange.Select
xlRange.Copy
'Instantiate Word and open the "Test" document.
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordDocument)
wdDoc.Application.Selection.Find.Execute "Table 1. Summary", MatchCase:=True
wdApp.Selection.MoveDown Unit:=wdLine, Count:=2, Extend:=wdMove
wdApp.Selection.PasteExcelTable False, False, False
wdDoc.Tables(1).AutoFitBehavior wdAutoFitWindow
'Save and close the Word doc.
With wdDoc
.Save
.Close
End With
wdApp.Quit
'Null out the variables.
Set wdRange = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
End Sub
Very probably, the reason is that you've set a Refernce to the Microsoft Word library for version 2016. When you open and run the project in an earlier version, the reference doesn't change to the Microsoft Word library for that version. This is expected behavior.
To fix the problem you can either
Open the project in the earliest version of Office (2007,
apparently). Go to Tools/References in the VBA Editor and select the
Microsoft Word library for that version. Test, then save.
Office applications will change References to a newer version, but they don't do so the other way around. That's why it's always recommended to develop using the oldest version of Office the project should work in.
Don't use named arguments in the method calls. Remove, for example, MatchCase:=, Unit, Count, Extend. In addition, don't use the Word enumerations: wdLine, wdMove, wdAutoFitWindow- these all have numerical equivalents, use those instead.
This is known as "late-binding", which makes your project independent of the version of Word. You can then completely remove the Reference to the Microsoft Word library.
In order to find out the numerical equivalents you can look up the enumerations in the VBA Object Browser (F2 in the VBA Editor), look them up in the Word VBA Help or query them in the VBA Editor Immediate Window (Ctrl + G) using syntax like this: ?wdLine and then press Enter to execute.

Resources