Word gets stuck during export via Excel VBA - excel

My Excel VBA script contains an export function which results in one Word document of about 12 pages.
On my private computer, this works.
On my company's laptop this seems to take too long and probably some kind of Word watchdog is triggered. Word gets stuck after about 75% of the code and the message "Word has stopped working" pops up.
I determined the point where it gets too much for Word to handle. As the export code is quite extensive and also contains several company and project details that I don't want to reveal, I prefer to not post it here.
Here is the snippet at which Word gets stuck:
ThisWorkbook.Worksheets("Backup - Do not change").Shapes("companyLogo").Copy
With wdFrontHeaderTable
.rows.Height=30
With .Cell(1,1).Range
.Paste
.ParagraphFormat.Alignment=0
End With
With .Cell(1,1).Range.InlineShapes(.Cell(1,1).Range.InlineShapes.Count)
.LockAspectRatio=msoTrue
.Width=120 'this one still works
End With 'here, the error occurs
End With
If I set one before that point and then run the two halves of code, one after another, it works.
If I uncomment the whole block, the error occurs in the next block.
The code does what it is supposed to do, even on the company laptop. I guess it just takes too long and the watchdog "thinks" Word was stuck.
Is there a way to disable the watchdog or another way to solve this?
I tried Application.Wait (1000).
Word is initialized by
Dim wdApp As Object
Dim wdDoc As Object
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Add

Related

Excel VBA Using GetObject for Word Document causes Source Application May Be Busy Error

Alright, so I'm try to reference an open Word document. But no matter what I do it stalls out and causes an error. The error takes 20-30 seconds before it pops up
"The object is not responding because the source application may be busy"
Dim oWord As Object
Set oWord = GetObject(, "Word.Application")
Debug.Print oWord.Documents.Count
Just a simple code block like above when I try Documents.Count it errors out. So I can't do anything with the GetObject object. Anyone have any clue on how to solve this problem?
Thanks
I've tried everything I can find on the Internet. I can open the file using CreateObject, but once it is open I cannot access it.
SOLVED
I'm an idiot. So I went to the task manager and it turns out there were like 20 Word instances that were created through my testing processes, so the GetObject was just timing out. When I closed all the instances, then opened one instance and ran the GetObject it worked and Documents.Count gave the correct answer.
Sorry for wasting your time!!
Your code works just fine for me - provided Word is running - returning a result after about 1 second. What it lacks is code to start Word if it isn't already running, in which case it errors out.
What you need is something like:
Dim wdApp As Object, bStrt As Boolean
' Test whether Word is already running.
On Error Resume Next
bStrt = False ' Flag to record if we start Word, so we can close it later.
Set wdApp = GetObject(, "Word.Application")
'Start Word if it isn't running
If wdApp Is Nothing Then
Set wdApp = CreateObject("Word.Application")
If wdApp Is Nothing Then
MsgBox "Can't start Word.", vbExclamation
Exit Sub
End If
' Record that we've started Word, so we can terminate it later.
bStrt = True
End If
MsgBox wdApp.Documents.Count
Perhaps you should check in Task Manager for an orphaned Word session running in the background. Other than that, you may need to restart Windows. If the problem persists, you may need to repair your Office installation.

Excel VBA hangs when expanding [+] workbooks object variable in locals window

I'm having a problem trying to debug some code I've written that opens a shared Excel file from SharePoint (in desktop Excel app), scrapes schedule data, makes a few changes, saves and closes that file, then populates the scraped data into the current workbook formatted as a calendar.
As is typical, the code executes fine for me, but only works about 50% of the time when another user runs it. I'm still searching for fixes to those bugs - they are not the reason for my question today. I'll try as best I can to describe my problem and hopefully someone can tell what I'm doing wrong.
First step I do is to check whether the SharePoint file exists and if so, open it (no problems/errors typically encountered here for myself or anyone else):
Sub getcalendardata()
...define variables...
Application.EnableEvents = False
Application.ScreenUpdating = False
schedule = "https://mycompany.sharepoint.com/sites/Schedule/Shared Documents/Schedule.xlsx"
If URLExists(schedule) = 0 Then
MsgBox "Schedule not found. Check internet connection, login to Office 365, and try again."
Exit Sub
End If
Set schedulewb = Workbooks.Open(schedule, False, False)
schedulewb.AutoSaveOn = False
Application.WindowState = xlMinimized
Set schedulews = schedulewb.Worksheets("Design")
...more code here...
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
Function URLExists(url As String) As Boolean
Dim Request As Object
Dim ff As Integer
Dim rc As Variant
On Error GoTo EndNow
Set Request = CreateObject("WinHttp.WinHttpRequest.5.1")
With Request
.Open "GET", url, False
.Send
rc = .StatusText
End With
Set Request = Nothing
If rc = "OK" Then URLExists = True
Exit Function
EndNow:
On Error Goto 0
End Function
*** Occasionally, I run into issues with the cached file in MS Office's Upload Center becoming out-dated and asking to save a copy or discard changes, but that is a problem for another day.
The main problem I've come here for is that after stepping through the Workbooks.Open line, if I open the "Locals Window" to view the stored variables and try and expand the Workbook object "schedulewb" (Here:
Locals Window during code execution), code execution seems to stop or go into an infinite loop. It's like VBA is trying to expand the schedulewb object to display the properties, but isn't getting a response, so it just waits. I've not been patient enough to see if it ever self recovers.
The only thing I see is that the Locals Window schedulewb line goes blank (like it's trying to expand) and I can no longer step through, continue, or reset/end the code execution. I can however, break/pause the execution, at which point, schedulewb returns to the Locals Window list and I'm able to expand it with a very brief delay. Restarting or resetting code execution after this just puts the program into the previous stall pattern and the only recovery option (besides waiting potentially forever) is to close and restart excel via Task Manager. Interestingly, the actual Schedule Workbook I'm trying to peak inside now shows up in the Office Upload Center as a pending upload or having just been synced.
I've tried bypassing SharePoint by opening a local version of the Schedule Workbook saved to my computer, and as expected, I can interact with the Locals Window variables without consequence.
Is there something wrong with setting a SharePoint Workbook to a variable like I've done?
Has an upload/refresh been triggered by me trying to inspect the object properties, causing some other uncontrollable VBA/SharePoint event to infinitely loop in the background?
Could this be connected somehow to the Upload Center cache headache that I think is unrelated?
Thank you in advance for any insight...

Run-time error -2147023170 (800706be) when copy-pasting images from Excel to Word

I am trying to copy/paste some images from my Excel sheet to a word file. Sometimes, it works flawlessly, but often I run into the great Run-time error '-2147023170 (800706be)': Automation error. The remote procedure call failed. message. Google showed my that I'm not alone with this error and that it often results from the fact that e.g. ranges are not precisely defined.I think they are in my project, however.
Here's my code:
Dim wdDoc As Object
Dim wdApp As Object
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Add
Dim wdImg As Object
ThisWorkbook.Worksheets("Backup - Do not change").Shapes("companyLogo").Copy
With wdDoc.Sections(1).Headers(2).Range
.PageSetup.DifferentFirstPageHeaderFooter = True
.Paste
Set wdImg = .InlineShapes(.InlineShapes.Count).ConvertToShape
With wdImg
'some specifications
End With
End With
ThisWorkbook.Worksheets("Backup - Do not change").Shapes("projectLogo").Copy
With wdDoc.Sections(1).Headers(2).Range
.Paste
Set wdImg = .InlineShapes(.InlineShapes.Count).ConvertToShape
With wdImg
'some specifications
End With
End With
Application.CutCopyMode = False
The error always occurs at .Paste. I already tried .PasteSpecial DataType:=8 and various other things but it didn't help. Any help is very welcome!
Okay so instead of pasting directly to the header range, I now created a table within the header and paste the images into two different cells. Since then I've successfully run the code for more than 10x so it seems like this fixed the issue (I hope it stays like this). Still not sure what caused it, though.
I want to add to this because this was one of the first posts I come across when having a similar issue. The solution at least for me was using copypicture and pastespecial as explained here:
Stack Overflow
Despite much searching this thread never showed up for me until I started to type a question and it showed up in the list of similar questions. Hopefully this can save someone else the massive headache that this was for me to solve.

How to release an Aspen object and clear memory

This is my first time using such forum.
I have exactly the same question as here:
How to release an object and clear memory in VBA
In this thread, the question was unfortunately not solved...
With Excel VBA I connect to another program (namely Aspen EDR). For that purpose I have an according Add-In installed. To access Aspen EDR I need to add an object. After I'm done I want to release the object to save some memory. First thing I tried is this:
Dim ObjEDR As BJACApp
Dim Path As String
Path = 'assume this is the correct path to the file i want to open
Set ObjEDR = New BJACApp ' Create the BJAC object
If Not ObjEDR.FileOpen(Path) Then
MsgBox "Can't open file!"
End If
'...
Set ObjEDR = Nothing
After I set the object nothing, Excel does not release the memory (as I can see in my task manager). Of course after a few hundred iterations (I have to open a lot of these files) I get an error message, that Excel is out of memory. I read a few threads and apparently nothing only deletes some kind of reference to the object but not the object itself, so I tried adding fileclose
'...
ObjEDR.FileClose
Set ObjEDR = Nothing
When executing the FileClose I can see that a little memory is released (0.5 of 3MB) but still there is a lot of memory accumulating.
Also when not using the "Now" it is not working and I get "runtime error'424': Object required" when executing Set ObjEDR = BJACApp
I also read about "pointers" that might cause the staying memory increase, but how can I find and clear/delete them?
Does anyone has an idea?
I would really appreciate it!
If .Quit (or the object's equivalent) and setting the object to Nothing is not working for you, then you could try relying on VBA's garbage collector to do the job.
Essentially what this means is that you would need to split the sub in two, have the main sub, and within that sub call the sub that will open and close your object. Hopefully, upon the second sub exiting, VBA will clean up those objects.
Sub Main()
Dim filePath As String
For Each [..] In [..] ' Or use a Do...Loop
filePath = 'assume this is the correct path to the file i want to open
openObj filePath 'call the sub below
Next [..]
End Sub
Sub openObj(ByVal Path As String)
Dim ObjEDR As BJACApp
Set ObjEDR = New BJACApp ' Create the BJAC object
If Not ObjEDR.FileOpen(Path) Then
MsgBox "Can't open file!"
End If
[...] 'your code to perform the needed actions with your obj
ObjEDR.FileClose
Set ObjEDR = Nothing
End Sub
I don't know anything about this object, but you should also try .Quit and .Close
Another method is to not create a new object for each path. Place the Set ObjEDR on the outside of your loop, and utilize the same object every time you open the new file.
Ok, to those who are interested:
The support of Aspen Tech told me that
ObjEDR.dispose()
should work, but just for versions above V8.4.
So this did not solved my problem and I built a workaround using MATLAB which opens and closes Excel after each run. So I loose time opening and closing the Excel file, but the memory of excel is not increasing until it stops working.

Word.Application (Office 2016) object .quit() method hanging in LS

I have a scheduled LotusScript agent that runs on a client (9.0 Social edition.) One of its purposes is to open a Word document and save it as PDF, but that's not really important. Here's the relevant code snippet
Declarations
Dim wrdApp as Variant
Sub Initialize
[Getting the usual Notes Session, Database, View values]
Set wrdApp = createObject("Word.Application")
wrdApp.visible = True
starthere:
'we check to see if there is anything that has been deferred
Set v = db.GetView("RIT")
strStatus = "Success"
Set doc = v.Getfirstdocument()
If (doc Is Nothing) Then Exit Sub
[Snip]
End Sub
Sub Terminate
wrdApp.visible = True
Dim quitCode As Variant
quitCode = 0
Call wrdApp.quit(quitCode)
Print "Quit called, waiting 3 seconds"
' Wait a couple seconds
Sleep(3)
Print "Done waiting, setting wrdApp to Nothing"
Set wrdApp=Nothing
Print "Exiting agent"
End Sub
The problem I'm having is that since we upgraded to Office 2016, sometimes the agent will never terminate. In the log I see "Done waiting, setting wrdApp to Nothing" but not "Exiting agent." I'll wind up with a Word window open (but no documents of course) and when I look in Task Manager, I see a WINWORD.EXE running with 0% CPU and 2 or 3 seconds of CPU time. And of course just to add to the intrigue, this doesn't happen every time either. And since the agent never ends, all other scheduled agents get held up until I kill the zombie Word instance. I've tried all the suggestions I can find (you'll notice I make Word visible and use a Variant as the parameter to Quit, and I even threw in the sleep(3) out of desparation), but none have made any difference. We never had this problem with Office 2010 (even when the agent code was far sloppier.) Also, the problem can happen whether or not I actually open a Word document. Is there a solution? Or is going back to O2010 the only option?
Sorry for the delay. I developed a wrapper class that can handle both Word and OpenOffice files "transparently". Parts of it you'll find below. I never had complaints from my client that the code no longer works, but that can also be due to the fact that they use the library to open a document using a template, then fill the document with data and then leave the document open.
One difference at first glance: I use Close where you have Quit.
-- to open a document
Function CreateMSWordDocument As Variant
Dim msWord As Variant
On Error Goto CreateNewInstance
Set msWord = GetObject("", "Word.Application")
Done:
Set CreateMSWordDocument = msWord
Exit Function
CreateNewInstance:
Print "Loading Microsoft Word.... Please Wait...."
Err = 0
Set msWord = CreateObject("Word.Application")
Print "Microsoft Word Loaded"
Resume Done
End Function
Set wdDoc= CreateMSWordDocument
-- to close it again:
Sub Close
Call wdDoc.Close
End Sub
I don't have more info for you than the above...
I am not sure if this is still relevant to you.
I have used Word for ages like the way you do (just wrapping it in a Class). However, I have experienced the exact same problem...
The solution was to do NOTHING once I had closed the document - then the WINWORD task just silently quits in the background!
HTH
/John
As a way of update/answer this question, I gave up looking for the real answer and instead wrote a C# program that looks for any instance of WINWORD.EXE that has been running for longer than 15 minutes and kill the process. Then I use the Task Scheduler to kick that program off every 15 minutes. It's crude and ugly, but it put out the 4-alarm fire I had before.

Resources