The usual approach to create a Word document from Excel VBA:
Set WD = CreateObject("Word.Document")
results in an error when run with Excel 2011.
Any idea how a Word document can be created in Excel 2011 with VBA?
(I do not want to use AppleScript as I want the program to be able to run on PCs also.)
The following code, based on the suggestion by bretville, seems to work both on mac (tested on Excel2011) and on pc (tested on Excel2007) and can be run repetedly, thus allowing creation of multiple Word files. What is required for the code to work under Excel2011 (mac) vba is a means to test if Word already is running or not. The approach is perhaps not the most elegant, but it works.
Dim word As Object
Dim doc As Object
On Error Resume Next
Set word = GetObject(, "word.application") 'gives error 429 if Word is not open
If Err = 429 Then
Set word = CreateObject("word.application") 'creates a Word application
Err.Clear
End If
word.Visible = True
Set doc = word.documents.Add
You may interchange the two Set word statements, which might seem preferable as no error code handling becomes necessary when run on pc, but the code for some reason then runs terribly slowly on the mac.
For a PC I would do this:
Dim word As Object: Set word = CreateObject("word.application")
word.Visible = True
Dim doc As Object: Set doc = word.documents.Add
Related
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.
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/
I've been trying to solve this error for a while, and nothing I've found online has seemed to help. Basically I'm running a script in excel VBA that opens a word document, and then opens the Save As dialog box so that I can save the file with the name / location of my choosing. It's at this point that I get the run time error 5.
I'm using the the Do Loop to try to get around the error, and it worked for a while. But for some reason the problem is back now and I have no idea why.
I've added a Do Loop that keeps the code from moving forward until the file has a name. This worked for a while but mysteriously stopped working after a few hours
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Word isn't already running
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdDoc = wdApp.Documents.Open(OFile)
'Clear the variable that contains the file path/name
SveReportName = ""
'Save word document as a new file
Set SveReport = wdApp.ActiveDocument.Application.FileDialog(msoFileDialogSaveAs)
With SveReport
' 3 is for 97-2003 - include for 2010, remove for 2003
.FilterIndex = 3
.Show
SveReportName = SveReport.SelectedItems.Item(1)
'This Do statement is here so that VBA just keeps adding 1+1 until the user has had time to name the tech report file, it should stop Run Time Error 5 from appearing
Do
a = 1 + 1
Loop Until IsNull(SveReportName) = False
wdDoc.SaveAs SveReportName
End With
Any idea what else might be going on?
Thanks in advance!
Have a read of the MS docs on the object you're using, and specifically its note about the execute method which should be used right after the show method for a Save As:
https://learn.microsoft.com/en-us/office/vba/api/office.filedialog.show
I think it reduces your 'save' code to something like this, though I haven't tried it:
'Save word document as a new file
Set SveReport = wdApp.ActiveDocument.Application.FileDialog(msoFileDialogSaveAs)
With SveReport
.FilterIndex = 3
if .Show = -1 then .Execute
End With
I stuck into a stupid error within my VBA code.
situation: create a Word Document out of Excel with a Word Template
problem: the Word Document does not open every time
If Word is still open (but in background) the code works fine.
If Word is closed the code opens Word but not the Document.
Word is open and active in the "new Document" section.
Var wrdDoc (in my code) is empty.
After this first try I close Word and run the code again it works completely fine.
This two steps I can repeat permanently. Only in the second run with a closed Word it works fine.
Before and after the code I have some other thinks, but that could not affect the Word Document.
System: MacBook Pro, macOS Mojave (10.14.2), Microsoft for Mac Version 16.20
Normally the arguments "NewTemplate:=True, Visible:=True" are not needed, but without them the document does not appear in any try.
Dim wrdDoc, wrdApp
On Error Resume Next
Set wrdApp = GetObject(, "word.application") 'gives error 429 if Word is not open
If Err = 429 Then
Set wrdApp = CreateObject("word.application") 'creates a Word application
Err.Clear
End If
wrdApp.Visible = True
Set wrdDoc = wrdApp.documents.Add(template:="/<path>/template.dotx", _
NewTemplate:=True, Visible:=True)
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.