Copy Excel data to Word after Office 2016 upgrade from 2010 - excel

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/

Related

I can't update worksheets objects links on powerpoint VBA - OneDrive Folder

I've already read in the forums but noone has my exactly problem, so here we go.
I have my excel and powerpoint files in a OneDrive folder (the Powerpoint is in subfolder), the powerpoint has 100 links.
So, in a forum someone suggested that to get the local OneDrive path, you should turn off the process. I did it.
I have to have the excel file open, because the processing time is really slow if the excel is closed. So If I have opened the excel file and run the macro (in other folder diferent to OneDrive) it runs ok, but if I try to do the same but in the OneDrive folder, it generated the next error into the code line pptShape.LinkFormat.Update:
Error -2147188160 (80048240) in runtime. LinkFormat (unknown member):
Invalid request. The linked file was unavailable and could not be
updated
If I have the excel file closed, the macro runs ok, but the process is so slow (almost 30 minuts), because it open and close the excel a hundred times.
does anyone knows why it happened? How can I fix it? I'll appreaciate your help. here is the code to update the links
Sub updatelinks_1()
Call Shell("cmd.exe /S /C" & "%LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /shutdown")
Application.DisplayAlerts = ppAlertsNone
Dim pptPresentation As Presentation
Dim pptSlide As Slide
Dim pptShape As Shape
'Set the variable to the PowerPoint Presentation
Set pptPresentation = ActivePresentation
'Loop through each slide in the presentation
For Each pptSlide In pptPresentation.Slides
'Loop through each shape in each slide
For Each pptShape In pptSlide.Shapes
'Find out if the shape is a linked object or a linked picture
If pptShape.Type = msoLinkedOLEObject Then
Dim name, path1, path2, source, begin, search1, cells As String
Dim limit1 As Integer
name = pptShape.LinkFormat.SourceFullName
limit1 = InStr(1, name, "!")
cells = Right(name, Len(name) - limit1)
search1 = "subfoldername"
path1 = Application.ActivePresentation.FullName
begin = InStr(1, path1, search1)
begin = Left(path1, begin - 1)
file1 = Dir(begin & "*.xlsm")
source = begin & file1
End If
path2 = source & "!" & cells
pptShape.LinkFormat.SourceFullName = path2
'update method. code line where generate error
pptShape.LinkFormat.Update
End If
Next
Next
'Update the links (If I use this method on OneDrive folder, it doesn't work and broke all the links because replace the Link name with only the excel file name, not the sheets and cells)
' pptPresentation.UpdateLinks
Call Shell("cmd.exe /S /C" & "start %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /background")
Set pptPresentation = Nothing
Set pptSlide = Nothing
Set pptShape = Nothing
Application.DisplayAlerts = ppAlertsAll
End Sub
Good morning everyone.
As I have not seen the solution, I'd like to add my 2 cents.
I have had a similar issue, on a win10 Platform running Office 365.
In my case both files are on the same laptop.
I have seen that the powerpoint VBA procedure to update the path takes a long time by default. ( around 4 Minutes for me as there are 22 linked Objects).
One can speed it up by manually open the target excel file before launching the Powerpoint VBA.
It becomes effectively faster but I hit the issue where for each link the ppt vba procedure tries to update, we get a pop up window telling us that Excel can't open 2 files with same name.
I've tried to add in the PowerPoint VBA procedure : Application.DisplayAlerts = False , but is logically inefficient as applies to the PPT application and not to the Excel app !
I finally found one quick (and logic) solution :
at the beginning of the PowerPoint VBA, I ask user to locate the target excel file :
Set XlApp = CreateObject("Excel.Application")
ExcelFile = XlApp.GetOpenFilename(, , "Would you please locate your excel File")
And after, I just Open the target file, and set it with displayLAerts to False.
XlApp.Visible = True
Set xlWorkbook = XlApp.Workbooks.Open(ExcelFile, True, False)
Doing so, I no longer get warnings.
Full source code available .
Wish you a nice day !

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.

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.

Issue with late binding

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.

Create Word file from Excel 2011

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

Resources