I have an application that first creates an invisible application:
Dim ExcelApp As Object
Set ExcelApp = CreateObject("Excel.Application")
ExcelApp.Visible = False
ExcelApp.ScreenUpdating = False
ExcelApp.DisplayAlerts = False
ExcelApp.EnableEvents = False
And then proceeds to use it to open files invisibly:
Do While fileTitle <> ""
Dim dataWorkbook As Workbook
Set dataWorkbook = ExcelApp.Application.Workbooks.Open(folderPath & fileTitle)
At the end of the operations with the file macros closes the file:
dataWorkbook.Close
fileTitle = Dir()
Loop
At the end of the sub macros closes the application:
ExcelApp.Quit
Set ExcelApp = Nothing
End Sub
However, if an error occurs before the file is closed, the invisible file and the application would never be closed and would continue to linger in operation systems not only eating away the memory and resources, but also preventing from doing any operations with the opened filed - renaming, opening or editting it.
I wonder if there is a way to close both the file and the application if an error occurs - in the current macros or to create a separate macros that detects invisible applications no variable points to and closes it.
At the top of your procedure use an error handler like
Set ExcelApp = CreateObject("Excel.Application")
On Error Goto CLOSE_FILE_ON_ERROR
'With that line you tell VBA to jump to the closing part if an error happens
and use this goto marker before you close the file.
CLOSE_FILE_ON_ERROR:
ExcelApp.Quit
End Sub
Note: You don't need to Set ExcelApp = Nothing because Excel does this automatically on End Sub.
Edit due to comments
If you need to show error messages or something then your code has to be extended like this:
ExcelApp.Quit 'This is needed to regularly quit if there is no error
Exit Sub 'Don't run into error handling if there was no exeption
CLOSE_FILE_ON_ERROR:
Application.StatusBar = "Error occured"
ExcelApp.Quit 'This is needed to quit after an exeption if there is an error
End Sub
You can try the below code where I kill the application like Excel, Chrome and Internet Explorer. You can use the below code with the On Error Goto error handler.
Public Function fnkilltask()
Dim objWMIService
Dim colProcessList
Dim objProcess
Dim strComputer
strComputer = "."
Set objWMIService = GetObject("winmgmts://./root/cimv2") ' Task mgr
Set colProcessList = objWMIService.ExecQuery ("Select * from Win32_Process Where Name in ('EXCEL.EXE','Chrome.exe','iexplore.exe') ")
For Each objProcess in colProcessList
objProcess.Terminate()
Next
End Function
Related
I have an access database which prints a label as a word document. The word document is filled using the information from my access database and then closed. This works on my personal laptop and prints every time. When I transfer this to my work laptop it works the first time and then fails as the document has remained open. The document does not show up in the processes in task manager, my laptop is using office 365 and my work laptop is at office 2016 is this a version issue? Code below. If this is completely wrong could you please suggest the fix
Dim appWord As Word.Application
Dim doc As Word.Document
Dim thepath As String
thepath = CurrentProject.Path
'Avoid error 429, when Word isn't open.
On Error Resume Next
Err.Clear
'Set appWord object variable to running instance of Word.
Set appWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
'If Word isn't open, create a new instance of Word.
Set appWord = New Word.Application
End If
Set doc = appWord.Documents.Open(thepath & "\label.docx", , False)
'ActiveDocument.Tables(1).Cell(1, 1).va Me.PartNumber
'
'ActiveDocument.FormFields(fldPartNumber). = Me!PartNumber
If Selection.FormFields.Count >= 1 Then
MsgBox Selection.FormFields(1).Name
End If
ActiveDocument.FormFields("Text1").Result = Me.PartNumber
ActiveDocument.FormFields("Text2").Result = Me.SerialNumber
'MsgBox (ActiveDocument.FormFields("Text1").Result)
ActiveDocument.FormFields("Text10").Result = Me.BatchNumber
ActiveDocument.FormFields("Text7").Result = Me.Qty
ActiveDocument.FormFields("Text6").Result = Me.Lifex
ActiveDocument.FormFields("Text3").Result = Me.Station
ActiveDocument.FormFields("Text4").Result = Me.Store
ActiveDocument.FormFields("Text5").Result = Me.Bin
ActiveDocument.FormFields("Text11").Result = Me.Description
'.FormFields("fldCountry").Result = Me.Country
' FormFields("fldPhone").Result = Me.Phone
'.FormFields("fldFax").Result = Me.Fax
activedocuments.FormFields.Visible = True
'ActiveDocument.FormFields.Activate
appWord.DisplayAlerts = False
doc.PrintOut Background = True
appWord.DisplayAlerts = True
'CreateObject("Shell.Application").Namespace(0).ParseName("C:\Boeing Ireland Serviceable Label editable form.docx").InvokeVerb ("Print")
Set doc = Nothing
doc.Close
appWord.Quit (True)
Set appWord = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description
'
End Sub
I think that the problem is the order that you are doing things at the end of the code. You should be closing/quitting objects before setting them to nothing. In addition, I would recommend that you have a single exit section that cleans up objects, regardless of whether there is an error or not. Something like:
Sub sFoo
On Error GoTo E_Handle
' Word automation code here
sExit:
On Error Resume Next
doc.Close
Set doc=Nothing
appWord.Quit (True)
Set appWord=Nothing
Exit Sub
E_Handle:
MsgBox Err.Description
Resume sExit
End Sub
Regards,
Ok, the answer here was a known issue in Microsoft Office automation the document was left open due to failing to reference an object. Microsoft issue 189618 was the reference that i used to fix this.
{Cause
Visual Basic has established a reference to Word due to a line of code that calls a Word object, method, or property without qualifying it with a Word object variable. Visual Basic does not release this reference until you end the program. This errant reference interferes with automation code when the code is run more than once.
Resolution
Modify the code so that each call to a Word object, method, or property is qualified with the appropriate object variable.}
My original error catch was to use on error resume next which allowed the real issue Runtime error 426 to be bypassed. This was due to the line of code setting the doc reference as
`enter code here`Set doc = Documents.Open(thepath & "\label.docx",,False,,,,True)'
as it doesn't reference appword it leaves an instance open. Hence my second time round open document. The fix was simple.
Set doc= appword.Documents.Open(thepath & "\label".docx",,False,,,,True) The code now works, below is a fully corrected and cleaned up version of the script which includes Applecores suggestion that was so kindly provided.
Private Sub Command67_Click()
On Error GoTo E_Handle
Dim appwd As Word.Application
Dim doc As Word.Document
Dim thepath As String
thepath = CurrentProject.Path
Set appwd = CreateObject("Word.Application")
appwd.Visible = True
Set doc = appwd.Documents.Open(thepath & "\label.docx", , False, , , , True)
doc.FormFields("Text1").Result = Me.PartNumber
doc.FormFields("Text2").Result = Me.SerialNumber & nullstring
doc.FormFields("Text10").Result = Me.BatchNumber & nullstring
doc.FormFields("Text7").Result = Me.Qty
doc.FormFields("Text6").Result = Me.Lifex
doc.FormFields("Text3").Result = Me.Station
doc.FormFields("Text4").Result = Me.Store
doc.FormFields("Text5").Result = Me.Bin & nullstring
doc.FormFields("Text11").Result = Me.Description
appwd.DisplayAlerts = False
doc.PrintOut Background = True
appwd.DisplayAlerts = True
doc.Close SaveChanges:=wdDoNotSaveChanges
Set doc = Nothing
appwd.Quit
Set appwd = Nothing
Exit Sub
sExit:
On Error Resume Next
doc.Close
Set doc = Nothing
appwd.Quit
Set appwd = Nothing
Exit Sub
E_Handle:
MsgBox Err.Description
Resume sExit
End Sub
I have a button on a form with the code below sitting in the form. It used to execute without a problem. Suddenly when clicking the button I now get this run time error:
Run-time error 91: Object Variable or With block variable not set in procedure cmdImportEDD_Click, line 0
I have tried commenting out individual lines in the code to find the problem. I ended up determening that the FileDialog part seems to be a problem somehow. However, after having added the If.. then part to it last time, the code worked again, but today the error is back.
To be clear, the error appears before the VBA code is executed (hence line 0) and Compile yields no errors either!
What is happening here that I'm not getting?
Private Sub cmdImportEDD_Click()
On Error GoTo cmdImportEDD_Click_Error
Dim fDialog As FileDialog
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
fDialog.AllowMultiSelect = False
fDialog.InitialFileName = GetDownloadFolder
fDialog.Show
If fDialog.SelectedItems.Count < 1 Then
Exit Sub
End If
Debug.Print fDialog.SelectedItems(1)
'Replace the selected file with the current one
Dim sOldFile As String
sOldFile = strTARGET_EDD_SALESFILE
Dim oFSO As FileSystemObject
Set oFSO = New FileSystemObject
oFSO.DeleteFile sOldFile
oFSO.MoveFile Source:=fDialog.SelectedItems(1), Destination:=sOldFile
'Perform the update
DoCmd.SetWarnings False
DoCmd.OpenQuery "qry_app_EDD", acViewNormal, acAdd
DoCmd.SetWarnings True
MsgBox "The data has been successfully imported!", vbOKOnly Or vbInformation, "Import Data: EDD"
On Error GoTo 0
Exit Sub
cmdImportEDD_Click_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure cmdImportEDD_Click, line " & Erl & "."
End Sub
The code for GetDownloadFolder:
Function GetDownloadFolder() As String
Dim objShell
Dim objFolder
Dim objFolderItem
Dim temp
Const DESKTOP = &H10&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(DESKTOP)
Set objFolderItem = objFolder.Self
temp = objFolderItem.Path
temp = Left(temp, Len(temp) - 7) & "Downloads" '<--- I believe this is the download folder
GetDownloadFolder = temp
End Function
Having canceled out the OnError I now get a debug error on the line Set objFolderItem = objFolder.Self
I managed to get my code working by replacing the somewhat more complicated Shell call in the GetDownloadFolder function with a simplerEnviron("USERPROFILE") & "\Downloads".
This has taken care of the run time error.
I have a problem with the following Code. What happens is that my PPT application crashes while running the code. It does not always happen and it happens in different parts of the code.
I tried the application.wait-method, but it did not work.
help is appreciated since I am already working on this for days -.-. Thanks in advance.
Option Explicit
Public myfilename As String
Sub filepicker()
Dim i As Variant
MsgBox ("In the following dialog please choose the current file")
Dim myfilenamepicker As FileDialog
Set myfilenamepicker = Application.FileDialog(msoFileDialogFilePicker)
myfilenamepicker.InitialFileName = "C:\Users\Michael\Desktop\Test PPT"
myfilenamepicker.Show
If myfilenamepicker.SelectedItems.Count <> 0 Then
myfilename = myfilenamepicker.SelectedItems(1)
End If
End Sub
Sub Saveas_PPT_and_PDF()
Dim PP As PowerPoint.Presentation
Dim sh As Variant
Dim company, strPOTX, strPfad, pptVorlage, newpath, newpathpdf As String
Dim Cell As Range
Dim pptApp As Object
Call filepicker
Application.ScreenUpdating = False
' set the dropdown from which the company Is Selected
Set DropDown.ws_company = Tabelle2
' the company is the value selected in the dropdown, stored in "C2"
company = DropDown.ws_company.Range("C2").Value
On Error Resume Next
Set pptApp = GetObject(, "PowerPoint.Application")
On Error Resume Next
If pptApp Is Nothing Then
Set pptApp = CreateObject("PowerPoint.Application")
End If
On Error GoTo 0
'loop through the companies in the dropdown menu
For Each Cell In DropDown.ws_company.Range(DropDown.ws_company.Cells(5, 3), _
DropDown.ws_company.Cells(Rows.Count, 3).End(xlUp)).SpecialCells(xlCellTypeVisible)
DropDown.ws_company.Range("C2") = Cell
pptVorlage = myfilename
Debug.Print (myfilename)
Set PP = pptApp.Presentations.Open(pptVorlage)
newpath = Replace(myfilename, "AXO", "" & Cell & " AXO")
PP.UpdateLinks
PP.SaveAs newpath
newpathpdf = Replace(newpath, "pptx", "pdf")
Debug.Print (newpathpdf)
PP.ExportAsFixedFormat "" & newpathpdf & "", ppFixedFormatTypePDF, ppFixedFormatIntentPrint
pptApp.Presentations(newpath).Close
Set PP = Nothing
Next
' this part below closes PPT application if there are no other presentation
' object open. If there is at least 1, it leaves it open
If IsAppRunning("PowerPoint.Application") Then
If pptApp.Windows.Count = 0 Then
pptApp.Quit
End If
End If
Set pptApp = Nothing
Set PP = Nothing
End Sub
Function IsAppRunning(ByVal sAppName) As Boolean
Dim oApp As Object
On Error Resume Next
Set oApp = GetObject(, sAppName)
If Not oApp Is Nothing Then
Set oApp = Nothing
IsAppRunning = True
End If
End Function
I don't see anything obviously wrong but I can give you a strategy for debugging.
You will want to test all major manipulations seperately. You will want to run each test in the debugger and have screenupdating on so you can see what happens:
test the filepicker
test GetObject/CreateObject - do you really need it? You already have PowrPoint open it seems;
test your loop with a single hardcoded value. What happens with the focus when opening a presentation?
try without UpdateLinks; try without SaveAs and try without Export (i.e. just open a presentation and close it again).
check if the presentation really closes, otherwise you might end up with lots of open presentations.
test closing the application
test reading from a dropdown box
test the IsAppRunning function. Note that it sets On Error Resume Next but does not reset it. Note it does not set IsAppRunning = False anywhere.
try relevant parts of the above in a loop with and without debugging to see what happens and see if it crashes - there could be a timing problem in the Office application, e.g. trying to manipulate a presentation while it is not yet fully loaded.
Minimising your code can help isolate the area that causes the problem. I hope this helps.
I am trying to develop code for save the file in SFTP server but error in Session and showing error as
user defined type not defined
I am not sure below code working or not and I copied the code from internet source.
Any suggestion would be appreciated.
Sub test()
Dim wb As Workbook
Set wb = "D:\Ashok\Work\Loan_Input_Template V8-Library.xlsx"
Dim mySession As New Session
' Enable custom error handling
On Error Resume Next
Call Upload(mySession, wb)
' Query for errors
If Err.Number <> 0 Then
MsgBox "Error: " & Err.Description
' Clear the error
Err.Clear
End If
' Disconnect, clean up
mySession.Dispose
' Restore default error handling
On Error GoTo 0
wb.Close SaveChanges:=True
'FileSystemObject.DeleteFile sPathName
End Sub
Private Sub Upload(ByRef mySession As Session, ByRef wb1 As Workbook) 'error line
Dim wb As Workbook
Set wb = Workbooks(wb1)
' Setup session options
Dim mySessionOptions As New SessionOptions
With mySessionOptions
.Protocol = Protocol_SFTP
.HostName = "103.231.8.66"
.UserName = "username"
.Password = "password"
.SshHostKeyFingerprint = "ssh-ed25519 256 df:94:44:56:1b:c2:75:8b:b4:58:3a:e2:ef:2e:0d:78"
End With
' Connect
mySession.Open mySessionOptions
' Upload files
Dim myTransferOptions As New TransferOptions
myTransferOptions.TransferMode = TransferMode_Binary
Dim transferResult As TransferOperationResult
Set transferResult = mySession.PutFiles(wb1, "/home/sftpcf/", False, myTransferOptions)
' Throw on any error
transferResult.Check
' Display results
Dim transfer As TransferEventArgs
For Each transfer In transferResult.Transfers
MsgBox "Upload of " & transfer.FileName & " succeeded"
Next
End Sub
Make sure you have followed the instructions for:
Installing the WinSCP .NET assembly and
Registering it for COM and
Using it from VBA.
I am experiencing an issue with Outlook automation,
To keep it simple I will first show you a shorter version of my code :
Sub test()
Dim GetOutlookApp As Object
Set GetOutlookApp = CreateObject("Outlook.Application")
End Sub
First, I do want to keep the late binding solution.
This sub launch Outlook in the taskbar (small icon). When I double click on it, a message pops up: "No active explorer object found" (title of the window: "Error"). Then the Outlook Inbox window opens when I click on OK.
My script is for end users so I don't want this message appears even if the user just has to click on OK (the rest of the main sub has no one issue).
I have to solve this problem to be able to send an email with outlook and to make sure the email is not in the Outbox folder.
What I am looking for is a way to open outlook, without this message, using late binding.
Below is the full code to open outlook before sending the email (source: ron de bruin). It works perfectly except the outlook message. The message pops up on this line:
obj.Session.GetDefaultFolder(olFolderInbox).Display
I tried AppActivate and others stuffs but I did not succeed and can't find any info on google about that!
Thanks for your help
Sub send_mail ()
Dim OutApp As Object
Set OutApp = OutlookApp() 'OPEN OUTLOOK
'Set OutApp = CreateObject("Outlook.Application") 'OPEN OUTLOOK simple solution
With ActiveSheet.MailEnvelope
...
End With
End sub
Public Function OutlookApp( _
Optional WindowState As Long = olMaximized, _
Optional ReleaseIt As Boolean = True _
) As Object
'***This sub is a part to the global way to open outlook before sending an email (prevent the outbox bug, email stucked into the outbox)
'***Source: http://www.rondebruin.nl/win/s1/outlook/openclose.htm, late binding mode
Static obj As Object
On Error GoTo ErrHandler
Select Case True
Case obj Is Nothing, Len(obj.Name) = 0
Set obj = GetObject(, "Outlook.Application")
If obj.Explorers.Count = 0 Then
InitOutlook:
'Open inbox to prevent errors with security prompts
obj.Session.GetDefaultFolder(olFolderInbox).Display
obj.ActiveExplorer.WindowState = WindowState
End If
Case ReleaseIt
Set obj = Nothing
End Select
Set OutlookApp = obj
ExitProc:
Exit Function
ErrHandler:
Select Case Err.Number
Case -2147352567
'User cancelled setup, silently exit
Set obj = Nothing
Case 429, 462
MsgBox "Err.Number OutlookApp: " & Err.Number
Set obj = GetOutlookApp()
If obj Is Nothing Then
Err.Raise 429, "OutlookApp", "Outlook Application does not appear to be installed."
Else
Resume InitOutlook
End If
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Unexpected error"
End Select
Resume ExitProc
Resume
End Function
Private Function GetOutlookApp() As Object
'***This sub is a part to the global way to open outlook before sending an email (prevent the outbox bug, email stucked into the outbox)
'***Source: http://www.rondebruin.nl/win/s1/outlook/openclose.htm, late binding mode
'On Error GoTo ErrHandler
Set GetOutlookApp = CreateObject("Outlook.Application")
ExitProc:
Exit Function
ErrHandler:
Select Case Err.Number
Case Else
'Do not raise any errors
Set GetOutlookApp = Nothing
End Select
Resume ExitProc
Resume
End Function
Use the Add method of the Explorers class to create a new instance of the explorer window. Then you need to call the Display method of the Explorer class (not Folder).
Sub DisplayDrafts()
Dim myExplorers As Outlook.Explorers
Dim myOlExpl As Outlook.Explorer
Dim myFolder As Outlook.Folder
Set myExplorers = Application.Explorers
Set myFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set myOlExpl = myExplorers.Add(myFolder, olFolderDisplayNoNavigation)
myOlExpl.Display
End Sub
This sub launch Outlook in the taskbar (small icon). When I double click on it, a message pops up: "No active explorer object found" (title of the window: "Error"). Then the Outlook Inbox window opens when I click on OK.
Typically you shouldn't see any icons in the task bar. Make sure that you have all the latest updates and service packs installed for the OS and Outlook. Also check out the list of running processes before automating Outlook - make sure that no Outlook instances running at the moment.
See How to automate Outlook from another program for more information.
Using the Eugene Astafiev code I have solved my issue! Thanks Eugene!
Here is the code:
Sub that send the email:
Sub Send_Mail()
'**This sub aims to send the mail that contains the job sheet
'Deactivate the screen updating : increase the speed and looks better
Application.ScreenUpdating = False
'Select the range of data
ActiveSheet.Range(FirstCol_JS & 1 & ":" & LastCol_JS & Firstrow_JS + nb_item_scanned - 1).Select
'Show the envelope on the ActiveWorkbook. This line prevents a bug (Method 'MailEnveloppe' of object '_Worksheet' failed. -2147467259, 80004005)
ActiveWorkbook.EnvelopeVisible = True
'Make sure outlook is opened or open it *****HERE IS WHY MY QUESTION*****
Call OutlookApp <------------------------------------------------
'Email error handling
On Error GoTo ErrorManagement
With ActiveSheet.MailEnvelope
'Subject is the title of the mail
.Item.Subject = "Job Sheet"
'Introduction is the content of the mail
.Introduction = "Hi John," & vbCrLf & _
"..." & vbCrLf & _
"Regards, The computer"
.Item.To = "alias#domain.com"
.Item.Send
End With
'Select the home page (main sheet)
'It is needed to activate the screenupdating so that the userform can be displayed on the sheet1
Application.ScreenUpdating = True
Else
'Normally, this message should never appear
MsgBox "You can't create a job sheet without any item. Nothing was done.", , "Action not allowed"
End If
'Exit sub before the error handling codes
Exit Sub
ErrorManagement:
'Activate the screen updating : be able to show that the outlook interface disappears
Application.ScreenUpdating = True
'Hide the outlook interface
ActiveWorkbook.EnvelopeVisible = False
'Activate the Excel windows so that the msgbox does not appear in the Windows taskbar
'This line is mandatory because the outlook interface is in front of the Excel workbook when it appears, so we have to activate again the Excel worbook
Call ActivateExcel
End Sub
Principal sub that manage to open Outlook
Sub OutlookApp(Optional ReleaseIt As Boolean = True)
'***This sub is a part to the global way to open outlook before sending an email (prevent the outbox bug, email stucked into the outbox)
'***Source: http://www.rondebruin.nl/win/s1/outlook/openclose.htm, late binding mode, and Eugene Astafiev http://stackoverflow.com/questions/31198130/vba-outlook-no-active-explorer-found
'Declaration of an object for outlook. The static mode allows to keep the object when this sub is launched more than one time
Static olObject As Object 'Early binding: Outlook.Application
'Declaration of variable objects to open the outlook window (prevent the email to be stuck in the Outbox folder)
Dim myExplorers As Object 'Early binding: Outlook.Explorers
Dim myOlExpl As Object 'Early binding: Outlook.Explorer
Dim myFolder As Object 'Early binding: Outlook.Folder
'Error handling
On Error GoTo ErrHandler
Select Case True
'If the olObject is nothing then try to create it
Case olObject Is Nothing, Len(olObject.Name) = 0
'This line will work if outlook is already opened, otherwise it will create an error and the code will go to ErrHandler
Set olObject = GetObject(, "Outlook.Application")
'If there is not already one opened windows of outlook
If olObject.Explorers.Count = 0 Then
InitOutlook:
'Open outlook window to prevent the email to be stucked in the Outbox folder (not sent)
Set myExplorers = olObject.Explorers
Set myFolder = olObject.GetNamespace("MAPI").GetDefaultFolder(6) 'olFolderInbox: 6
Set myOlExpl = myExplorers.Add(myFolder, 0) 'olFolderDisplayNoNavigation: 2, olFolderDisplayNormal:0
'Early binding code:
'Set myExplorers = Application.Explorers
'Set myFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
'Set myOlExpl = myExplorers.Add(myFolder, olFolderDisplayNoNavigation)
myOlExpl.Display
End If
End Select
'Delete the olObject variable is the ReleaseIt boolean is true
If ReleaseIt = True Then
Set olObject = Nothing
End If
'Possibility to set the OutlookApp function as the outlook object, if OutlookApp is declared like this: "Function OutlookApp(Optional ReleaseIt As Boolean = True) as Object"
'Set OutlookApp = olObject
ExitProc:
Exit Sub
ErrHandler:
Select Case Err.Number
Case -2147352567
'User cancelled setup, silently exit
Set olObject = Nothing
Case 429, 462 '429: outlook was not opened, the Set olObject = GetObject(, "Outlook.Application") code line above did not work
Set olObject = CreateOutlook() 'Launch the CreateOutlook function: CreateOutlook = CreateObject("Outlook.Application")
If olObject Is Nothing Then 'If the outlook object is still empty it means that there is a more serious issue (outlook not installed on the computer for example)
Err.Raise 429, "OutlookApp", "Outlook Application does not appear to be installed."
Else 'If olObject is no more nothing, go back to the code above and open the outlook window
Resume InitOutlook
End If
Case Else 'For any other error numbers
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Unexpected error"
End Select
Resume ExitProc
Resume 'For debugging
End Sub
Second sub that manage to open outlook
Private Function CreateOutlook() As Object
'***This sub is a part to the global way to open outlook before sending an email (prevent the outbox bug, email stucked into the outbox)
'***Source: http://www.rondebruin.nl/win/s1/outlook/openclose.htm, late binding mode
'Error handling
On Error GoTo ErrHandler
Set CreateOutlook = CreateObject("Outlook.Application")
ExitProc:
Exit Function
ErrHandler:
Set CreateOutlook = Nothing
Resume ExitProc
Resume 'For debugging
End Function
FYI here is the code to activate the Excel window
Sub ActivateExcel()
'***This sub aims to activate Excel windows (so that it's in front of the windows)
'Set variable title equal to exact application window title
Dim ExcelTitleCaption As String
ExcelTitleCaption = Application.Caption
'Activate Microsoft Excel
AppActivate ExcelTitleCaption
End Sub
Thanks!! Topic solved