Application property under _Application Interface in Excel Object Model - vb.net

To create an instance of excel using VB.Net, we can write the following piece of code:
Imports System
Imports Microsoft.Office.Interop.Excel
Imports Word = Microsoft.Office.Interop.Word
Module Program
'declaration statements
Dim oXL As Microsoft.Office.Interop.Excel.Application
Dim oWB As Workbook
Dim oSheet As Worksheet
Dim oWord As Word.Application
Dim oDoc As Word.Document
Sub Main(args As String())
'Console.WriteLine("Hello World!")
oXL = CreateObject("Excel.Application")
oXL.Visible = True
oXL.DisplayAlerts = True
Console.WriteLine("Type returned by CreateObject: {0}", oXL.GetType())
oWB = oXL.Workbooks.Add
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add
Console.ReadLine()
oXL.Quit() 'Not getting the warning
oWord.Quit(False) 'Not getting the warning
End Sub
End Module
Till here all is good. However I also came across the following statement in the MSDN Link:
Use the Application property to return the Application object.
I checked and found that the APPLICATION property is a member of _Application interface, the usage criteria of which as per this link is mentioned below.
Use this primary interface only when the method you want to use shares the same name as an event of the COM object
However this statement is not clear to me. So can someone please explain (if possible with an example) when should I use the Application property of the _Application interface to return an Application object? Also is the object returned by the Application property any different from the one being returned by createObject in the statement oXL = CreateObject("Excel.Application")?

Related

Macro used to run on Outlook 2013, now doesn't run on Outlook 2021 on a new computer

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.

Office application hangs during document opening via interop

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

Call Word VBA MsgBox function from Excel

Is it possible to call Word's MsgBox function from Excel VBA? I am having trouble doing this as MsgBox is not a method of Word.Application.
I have tried this:
Dim objWord As Word.Application
Set objWord = New Word.Application
Dim objDoc As Word.Document
Set objDoc = objWord.Documents.Add
objWord.Visible = True
objWord.Activate
Call objWord.Run("MsgBox", "Hello World") ' Or:
Call objDoc.Run("MsgBox", "Hello World")
But I get the error "Object doesn't support this property or method", no matter which 'Call' line I include.
I am trying to do this so that I can display a message box in front of the open Word document saying that the document rendering has completed. If I just call Excel's MsgBox then I have to click on the flashing button in the Windows Taskbar before I can see the message box.
The word document is generated entirely by my Excel macro.
Is this possible?
I have some functions that export modules and re-import them. It is configured now for PPT but was hacked together from Excel functions that I found. There is also a way to use VBA to write VBA. Both are fairly advanced though. Probably both sets of functions are available here:
http://www.cpearson.com/excel/vbe.aspx
However, that's probably overkill. This is probably your best bet, to use a popup instead of a VBA msgBox.
Sub Test()
Dim wdApp As Object
Dim shl As Object
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
wdApp.Activate
Set shl = CreateObject("wscript.shell")
shl.Popup ("Hello, world!")
Set shl = Nothing
Set wdApp = Nothing
End Sub
See also here for more detail about how to control it's timeout/etc.
Whats the best way to display a message box with a timeout value from VBA?
It is! The problem with the way that you're doing it is that the run function of the word application looks for macros with that name and runs them. The way that I was able to accomplish this is by making a subroutine in the word doc that creates the message box.
Public Sub Testing()
Dim objWord As Word.Application
Set objWord = New Word.Application
Dim objDoc As Word.Document
Set objDoc = objWord.Documents.Open("C:\whatnot\Stuff.docm")
objWord.Visible = True
objWord.Activate
objWord.Run ("Testing")
End Sub
Then in the Word document:
Public Sub Testing()
MsgBox ("Hello World")
End Sub

Open Excel file in VBA from Powerpoint

I'm trying to open the Excel file using VBA in Powerpoint 2010 with the help of following code.
Private Sub CommandButton1_Click()
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Workbooks.Open "C:\lol\Book1.xlsx", True, False
Set xlApp = Nothing
Range("A8").Value = "Hello"
End
But I'm getting the following error.
Compile Error
User Defined type not defined.
Am I missing something. Can anyone share the sample piece of code to open an excel file, change a cell value and close Excel file in Powerpoint 2007 and 2010 using VBA.
I have searched a lot and tried different pieces of code, but getting the same error everytime. :(
Thanks in advance. :)
Have you added a reference to the Excel Object Model? That would save you having to use the late bound objects (and you get the benefit of having the Intellisense help when you are coding).
You need to go to Tools -> References and check the "Microsoft Excel v.x Object Library" (I think that number changes depending on the version of office you are using.
Your code should work if you do that, you should also remove the
CreateObject("Excel.Application")
line and replace it with
Set xlApp = new Excel.Application
And move the
Set xlApp = nothing
line to the end of your subroutine.
The rest of your code looks fine to me.
Late binding code would be this
Private Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkbook = xlApp.Workbooks.Open("C:\lol\Book1.xlsx", True, False)
xlWorkbook.sheets(1).Range("A8").Value = "Hello"
Set xlApp = Nothing
Set xlWorkbook = Nothing
End Sub
It's better to use early binding though.

opening excel in vb.net error

what do you think is wrong with the commented line in my vb.net code below? it returns the error message "member not found". thank you.
Public Function tae(ByVal SourcePath As String)
Dim oxlApp As Excel.Application
Dim oxlBook As Excel.Workbook
Dim oxlSheet As Excel.Worksheet
oxlApp = CType(CreateObject("Excel.Application"), Excel.Application)
oxlBook = CType(oxlApp.Workbooks.Open(SourcePath), Excel.Workbook) //somethings wrong here
oxlSheet = CType(oxlBook.Worksheets(1), Excel.Worksheet)
oxlApp.Workbooks.Close()
oxlApp.Quit()
End Function
i tried to add the following references and its now ok:
ms excel x object library
ms office x object library
visual basic for applications