I am trying to open a file but the Office application hangs during document opening in VB.NET.
I have this code:
Dim oProp As Object
Dim strPropValue As String
Dim lngRetVal As Integer
Dim strmsg As String
Dim lngretcode As Integer
Dim strPropertyName As String
Dim oWordDoc As Word.Document
Dim ObjOfficeAPP As Object
ObjOfficeAPP = New Word.Application()
GetWORDKEYS = cstFAILURE
ObjOfficeAPP.DisplayAlerts = WdAlertLevel.wdAlertsAll
ObjOfficeAPP.Application.Visible = True
oWordDoc = ObjOfficeAPP.Documents.Open(FileName:=strpFileName, Visible:=False)
I have problems on the line:
oWordDoc = ObjOfficeAPP.Documents.Open(FileName:=strpFileName, Visible:=False)
The debugger hangs on the Documents.Open() call, and just stays there waiting - without firing any type of exception or error. We have looked in the event log but only found the following.
My problem is, how can I set to open this document and not to block on the line with the Documents.Open() call?
Here are few points that could help:
Don't use the Application property for setting the Visible property:
ObjOfficeAPP.Visible = True
Don't set the DisplayAlerts property before opening a document.
Use the System.Reflection.Missing.Value for missing arguments.
You may find the How to automate Word from Visual Basic .NET to create a new document article helpful which explains the required steps for automating Word and provides a sample code:
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add
Related
A few years ago I had a developer write a macro for me to print the current email as two pages per page rather than on two separate pages.
It used to run successfully on my old computer Win 10/Outlook 2013.
I now have a new computer Win10/Outlook 2021
It now comes up with a compile error "User defined type not defined" for the line
Dim wdApp As Word.Application
I only have a rudimentary grasp of VBA so am unable to solve this one. Any help would be greatly appreciated.
Code is as follows:
Option Explicit
Public Sub print_mail()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim Response As Integer
Dim msg As String
Dim strSubject As String
Dim currentItem As Object
Set objOL = CreateObject("Outlook.Application")
Set objSelection = objOL.ActiveExplorer.Selection
For Each currentItem In objSelection
If currentItem.Class = olMail Then
Set objMsg = currentItem
PrintFirstPage objMsg
End If
Next
Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub
Public Sub PrintFirstPage(Mail As Outlook.MailItem)
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim olDoc As Word.Document
Set wdApp = CreateObject("Word.Application")
Set wdDoc = wdApp.Documents.Add(Visible:=True)
Set olDoc = Mail.GetInspector.WordEditor
olDoc.Range.Copy
wdDoc.Range.Paste
' With wdDoc
' .PageSetup.Orientation = wdOrientLandscape
' End With
'wdDoc.PrintOut
wdApp.PrintOut FileName:="", Range:=wdPrintRangeOfPages, Item:= _
wdPrintDocumentWithMarkup, Copies:=1, Pages:="1-2", PageType:= _
wdPrintAllPages, Collate:=True, Background:=True, PrintToFile:=False, _
PrintZoomColumn:=2, PrintZoomRow:=1, PrintZoomPaperWidth:=0, _
PrintZoomPaperHeight:=0
wdDoc.Close False
wdApp.Quit
End Sub
Use an untyped variable:
Dim appWD as Object
appWD = CreateObject("Word.Application")
Or try to add the Word object library reference to the 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.
VBA macros are not designed for distributing on multiple machines. If you need to deploy your code on a wide range of machines you would better consider transforming your solution to Office add-ins - it can be a COM add-in or a web-based one. See Walkthrough: Create your first VSTO Add-in for Outlook for more information.
When you move your VBA code to another machine you need to make sure that all COM references are added as it was on your original machine.
In order to solve your 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 XX.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.
Note, you could also use the late binding technology which doesn't require adding COM references:
' No reference to a type library is needed to use late binding.
' As long as the object supports IDispatch, the method can
' be dynamically located and invoked at run-time.
' Declare the object as a late-bound object
Dim oWord As Object
Set oWord = CreateObject("Word.Application")
' The Visible property is called via IDispatch
oWord.Visible = True
So, to start an Word Automation session, you can use either early or late binding. Late binding uses either the Visual Basic GetObject function or the CreateObject function to initialize Word. See Using early binding and late binding in Automation for more information.
Receiving a Runtime Error '13' exception when creating a word application object. I also was experiencing relatively extreme delays (on the order of 20-30 seconds) of running prior to the exception. Any idea what this could be from? I searched Stackoverflow and I haven't seen anything that was very similar.
I have never worked with an word doc from excel before so this is something new to me.
Code Below:
Public Sub GetRawData()
'Meant to translate data from a raw word file and format into excel
Dim filePath As String
Dim objWord As Application
Set objWord = CreateObject("Word.Application")
Dim objDoc As Word.Document
'File management vars
Dim oneLine As Paragraph
Dim lineText As String
filePath = "U:\Research_Dev Docs\DevFolder\Word Doc Translation In Excel For Phys\testWordDoc.docx"
'Set word doc object using standard file directory and file name
Set objDoc = objWord.Documents.Open(Filename:=filePath, Visible:=True)
For Each oneLine In objDoc.Paragraphs
'Pull in each line and eventually parse
lineText = oneLine.Range.Text
'DEBUG OUTPUT TO THE SCREEN FOR TESTING
MsgBox (lineText)
Next oneLine
End Sub
I'm having a problem where when I use the Word.Application.Selection.Find set of commands, I run into a NullReferenceException. In this program I initialize a new Word document as such:
Dim wrdApp As Word.application = New Word.Application
Dim wrdDoc As Word.Document = New Word.Document
wrdApp.Visible = True
With wrdDoc
wrdApp.Selection.Find.ClearFormatting()
wrdApp.Selection.Find.Text = sequenceObject(i, 1, 1, 1).cat
wrdApp.Selection.Find.Forward = True
wrdApp.Selection.Find.Wrap = Word.WdFindWrap.wdFindContinue
wrdApp.Selection.Find.Execute
End With
When I have no windows open prior to the code running, I have no problem. If I have another word document open at the time, the error occurs at the first Find command; it used to occur at the ClearFormatting line. I commented it out, then it occurred at the Find.Text line. I have the correct object libraries referenced and imported.
I figured it out, I wasn't actually specifying which document to select. By using
wrdApp.ActiveDocument.ActiveWindow
I was able to solve the problem.
This isn't a crisis, because the script actually works just fine, but I need to implement it for an office wide process and I expect this issue will cause a bit more confusion with the less tech-savvy.
The following is intended to replace common citations that we use with links to the website where they can be found. So a reference to policy AP&P-X-A-1-100 automatically becomes a link to APP-X-A-1-100_issuance.shtml when the user hits a button.
The problem is, it only works if there's an open Word document in the background. If Word isn't open, I get one of three errors: "The Remote Server Machine does not exist or is not available" or "Automation Error: the remote call procedure failed" or "ActiveX Component Cannot Create Object". If try three times in a row, I can get any permutation of those three. I've never had revolving errors like this.
Any idea why Word is required for this to run?
Sub CitationPolicy()
Dim myInspector As Outlook.Inspector
Dim myObject As Object
Dim myItem As Outlook.MailItem
Dim rngStory As Word.Range
Dim myDoc As Word.Document
Dim mySelection As Word.Selection
Dim strItem As String
Dim strItem2 As String
Dim strLink As String
Set myInspector = Application.ActiveInspector
Set myObject = myInspector.CurrentItem
Set myDoc = myInspector.WordEditor
Set mySelection = myDoc.Application.Selection
For Each rngStory In ActiveDocument.StoryRanges
With mySelection.Find
.Text = "AP&P-*-[0-9]{3}"
.MatchWildcards = True
.Replacement.Text = ""
.Wrap = wdFindContinue
While mySelection.Find.Execute
strItem = mySelection.Text
strItem2 = Replace(strItem, "AP&P", "APP")
mySelection.Hyperlinks.Add Anchor:=mySelection.Range, _
Address:="http://www.oursite.com/" & strItem2 & "_issuance.shtml", _
TextToDisplay:=strItem
Wend
End With
Next rngStory
End Sub
Thats because you are referencing the WORD Application.
Outlook uses Word engine as word-editor but this has to be referenced as MailItem.GetInspector.WordEditor. Otherwise you are forced to create Word application or in your case work only if a word application is running.
Maybe have a look at this: msdn.microsoft.com/en-us/library/dd492012(v=office.12).aspx
Hope this helps.
I am getting an error when I run this app in VS 2010 (it works fine in VS 2008)
Private Sub GenerateInvoice()
Dim emptyObject As Object = System.Reflection.Missing.Value
Dim wordApp As New Word.Application
wordApp.Visible = True
Dim InvoiceDoc As New Word.Document
InvoiceDoc = wordApp.Documents.Add(InvoicePath, emptyObject, emptyObject, emptyObject)
Dim totalFields As Integer = 0
For Each mergeField As Word.Field In InvoiceDoc.Fields
The error occurs at the For Each line
"Object reference not set to an
instance of an object."
Am I missing something here?
Maybe the InvoicePath used in the instance run via VS2010 is invalid and so the call to Documents.Add fails?
Are you running both VS2010 and VS2008 on the same machine? And is the InvoicePath set to the exact same path in both instances?
Try
Dim InvoiceDoc As Word.Document
wordApp.Documents.Add(InvoicePath, emptyObject, emptyObject, emptyObject)
InvoiceDoc=wordApp.ActiveDocument