Excel application not closing from Outlook VBA function - excel

I'm writing a sort of homegrown ticketing system for myself in Outlook VBA, and I'm using Excel to store all the persistant data. I have a function written in Outlook to get some data from the .csv and return it. This is all working fine, but after I close the workbook, quit the application, and set the app to nothing I still have an Excel process running! Here is my code:
Private Function GetNewTicketNumber() As Integer
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
With xlApp
.Visible = False
.EnableEvents = False
.DisplayAlerts = False
End With
Dim FileStr As String
Dim NumberBook As Workbook
Dim TheRange As Range
FileStr = "C:\OMGITSAPATH.csv"
Set NumberBook = Workbooks.Open(FileStr)
Set TheRange = NumberBook.Worksheets(1).Range("A1")
GetNewTicketNumber = TheRange.Value
TheRange.Value = TheRange.Value + 1
NumberBook.Save
NumberBook.Close
xlApp.Quit
With xlApp
.Visible = True
.EnableEvents = True
.DisplayAlerts = True
End With
Set xlApp = Nothing
End Function
Is there something that I'm doing wrong here? My problem is similar to the one here, but I have disabled DisplayAlerts... What can I do to fix this problem?

Try fully qualifying your references to Excel, from xl_doesnt_quit
The problem presented here is exactly what you have. This line
Range("a1").Value = Range("a1").Value + 1
leave the xl instance open
The most common cause of the problem is a 'global' reference to the automated application. Unfortunately, under some circumstances it is possible to directly refer to an entity (property/method/object) of the automated object. This reference effectively is global to the calling application. Hence, the reference remains in place as long as the calling program is active. Consequently, the operating system will not end the automated application while the caller is active.
Re-cut code below (which also uses late binding - which rules out the unqualified possibility).
Pls change you path to suit.
code
Private Function GetNewTicketNumber() As Long
Dim xlApp As Object
Dim objWB As Object
Dim objWs As Object
Dim FileStr As String
FileStr = "C:\temp\test.xlsx"
Set xlApp = CreateObject("excel.application")
With xlApp
.EnableEvents = False
.DisplayAlerts = False
End With
Set objWB = xlApp.Workbooks.Open(FileStr)
Set objWs = objWB.Sheets(1)
GetNewTicketNumber = objWs.Range("A1")
objWs.Range("A1") = objWs.Range("A1") + 1
objWB.Save
objWB.Close
Set objWB = Nothing
xlApp.Quit
Set xlApp = Nothing
End Function

Related

Opening Excel file located in one drive

I need to open the excel file located in share point using Excel.Application
In Visual Basic 6, I am using following to open the excel file located in Sharepoint:
Shell "C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE https://livecnm-my.sharepoint.com/:x:/g/personal/sghimire_cnm_edu/EZwyv4Ot1_xEnIeT1SIADncBVtRQ0b6THoJj0eLrbpEjXQ?e=NgyEBD", vbNormalFocus
But i want to use Excel.Application instead of shell so, i can hide ribbon, status bar, formula bar and other stuff before excel file open.I have tried following but it not working:
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Workbooks.Open "https://livecnm-my.sharepoint.com/:x:/g/personal/sghimire_cnm_edu/EZwyv4Ot1_xEnIeT1SIADncBVtRQ0b6THoJj0eLrbpEjXQ?e=NgyEBD"
.Application.ExecuteExcel4Macro "Show.toolbar(""Ribbon"",False)"
.Application.DisplayStatusBar = False
.Application.DisplayFormulaBar = False
.Application.DisplayScrollBars = True
.Application.Visible = True
End With
Maybe you give this a try
Sub open_excel_from_one_drive()
Dim sfilename As String
Dim xl As Excel.Application
Dim xlsheet As Workbook
sfilename = "https://d.docs.live.net/78a58439bd7a4267/Investment%20Spreadsheet/Customer%20Management/Security%20Data.xlsm"
Set xl = Application
Set xlsheet = xl.Workbooks.Open(Filename:=sfilename)
End Sub
If you want to go on using your code then you could try
Sub dummy_Code()
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Workbooks.Open "https://d.docs.live.net/78a58439bd7a4267/Investment%20Spreadsheet/Customer%20Management/Security%20Data.xlsm"
.Application.ExecuteExcel4Macro "Show.toolbar(""Ribbon"",False)"
.Application.DisplayStatusBar = False
.Application.DisplayFormulaBar = False
.Application.DisplayScrollBars = True
.Application.Visible = True
End With
End Sub

VBA Closing a word document which has already been opened using another sub, bad file name error

I've set up code that opens a word document and closes excel, from the word document there is code to reopen excel and copy user data to a new sheet which I pull from for a form. This whole process works perfectly, the issue is trying to close the word document once I've finished my tasks.
I want to close the word document once I'm back in excel however everything I'm trying returns bad file name error when I try to reference the doc. I know for a fact that the file path is correct. I also know that you cant reference the open doc the normal way you would. I've substituted the variable filePath for privacy reasons.
Here is the code from word which is executed first
Sub sendTableToExcel()
Dim xlApp As Excel.Application
Dim xlWb As Excel.Workbook
Dim ws As Worksheet
Dim doc As Document
Dim tbl As Table
Set doc = ThisDocument
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWb = xlApp.Workbooks.Open(filePath)
Set ws = Sheets.Add
ws.Name = "temp"
Set tbl = doc.Tables(1)
tbl.Range.Copy
xlWb.Worksheets(ws.Name).PasteSpecial wdPasteText
ws.Visible = False
xlWb.Application.Run "pasteCopiedValuesFromRequestDocs"
xlWb.Application.Run "openRequestLanding", "Casual" //this is the where I'm trying to close the doc
Set xlWb = Nothing
Set xlApp = Nothing
Set tblRange = Nothing
Set tbl = Nothing
Set doc = Nothing
End Sub
and the sub from excel which is called from word
Public Sub openRequestLanding(requestType As String)
Dim wdApp As Word.Application
Dim doc As Word.Document
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
Set doc = wdApp.Documents(filePath)
doc.Close SaveChanges:=wdDoNotSaveChanges
Set wdApp = Nothing
Set doc = Nothing
RequestLanding.RequestTypeBox.Value = requestType
RequestLanding.Show
End Sub
You will have no success in closing the document as it is not open in the instance of Word that your code references. Your code in Excel needs to get the currently open instance of Word, not create a new one.
Change
Set wdApp = CreateObject("Word.Application")
to
Set wdApp = GetObject(, "Word.Application")

Outlook VBA: Activating a Workbook, Activating a Row, Inserting Copied Rows

I have an Outlook Macro that saves attachments based on a search of an e-mail inbox. The Aggregation File is then opened, then a loop opens the first of the saved attachments and copies the "AggregateThis" named range.
What I need to achieve is:
1). Activate the Aggregation File
2). Activate the Row where the result of the search for "END" is located
3). Insert the copied cells above end
The Outlook Object model is giving me trouble, this would be a total cinch in Excel VBA. Your help would mean so much!
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = False
.Workbooks.Open ("J:\Retail Finance\Varicent\General Teamshare Resources\Acting Mgr Assignment Bonus Aggregation.xlsx")
Dim x As Variant
i = -1
For Each x In AttachNames
Dim wb As Object
i = i + 1
Set wb = .Workbooks.Open("J:\Retail Finance\Varicent\General Teamshare Resources\Teamshare AAA\" & AttachNames(i))
Set wb = .Worksheets("Additional Assignment Bonus FRM")
'Copies the "Aggregate This" named range from the Individual File (i)
With wb.Range("AggregateThis")
.Copy
End With
'Switches focus to Aggregation File
Set wb = .Workbooks("J:\Retail Finance\Varicent\General Teamshare Resources\Acting Mgr Assignment Bonus Aggregation.xlsx")
With wb
.Activate '#1). I want to put focus on this file it throws an error
End With
'Find EndRow in the Aggregation File
Set wb = .Worksheets("Additional Assignment Bonus FRM").Cells.Find("End")
With wb
.ActivateRow '#2).This throws an error
.PasteSpecialInsertRows '#3). This doesnt work
End With
Next
The original code didn't work properly because, for .Activate to work, ScreenUpdating must be set to True (which it is by default).
Dim xlApp As Object
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
.DisplayAlerts = False
.ScreenUpdating = True '## Was set to False in code originally##
.Workbooks.Open ("J:\Retail Finance\Varicent\General Teamshare Resources\Acting Mgr Assignment Bonus Aggregation.xlsx")
Dim x As Variant
i = -1
For Each x In AttachNames
Dim wb As Object
i = i + 1
Set wb = .Workbooks.Open("J:\Retail Finance\Varicent\General Teamshare Resources\Teamshare AAA\" & AttachNames(i))
With xlApp
.Worksheets("Additional Assignment Bonus FRM").Range("AggregateThis").Copy 'Copies Range
End With
Set wb = .Workbooks.Open("J:\Retail Finance\Varicent\General Teamshare Resources\Acting Mgr Assignment Bonus Aggregation.xlsx")
With wb
.Worksheets("Additional Assignment Bonus FRM").Rows.Find("End").Select
.Worksheets("Additional Assignment Bonus FRM").Activerange.Paste '##This needs to be fixed##, will edit response soon.
End With
Next
End With
End Sub

How to retrieve data from Excel and add to Word

I have a Word template file that retrieves data from an Excel file to populate a form.
The code looks something like this:
Dim myXL As Object
Set myXL = Getobject("myfile.xls")
myXL.Application.Visible = True
myXL.Parent.Windows(1).Visible = True
This code works fine in Office 2010 and 2007, but when I try it in 2013, it gives run time error 9 which is an array subscript error. When I check the Windows array it has zero elements, so error is correct.
How do I achieve the same result in 2013?
The next bit of code attempts to access the Worksheets("mysheet") and if I skip the Visible = True line accessing the worksheet gives runtime error 1004.
Any help with fixing this would be greatly appreciated.
To make the code work on Office 2013 I added the line myXL.Activate before trying to make the Window visible. So the code becomes:
Dim myXL As Object
Set myXL = Getobject("myfile.xls")
myXL.Application.Visible = True
myXL.Activate
myXL.Parent.Windows(1).Visible = True
This fixed the run-time error, and the code went back to working well.
To retrieve data from an Excel
An Example would be...
Option Explicit
Sub ExcelData()
Dim xlApp As Object ' Application
Dim xlBook As Object ' Workbook
Dim xlSht As Object ' Worksheet
Dim FilePath As String
FilePath = "C:\Temp\Book1.xlsx"
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open(FilePath)
Set xlSht = xlBook.Sheets("Sheet1")
With ActiveDocument
.Content = xlSht.Range("A1").Value
End With
xlApp.Visible = True
Set xlApp = Nothing
Set xlBook = Nothing
End Sub

Can't add attachment to email using VBA

I am having a very strange problem with this code. The general purpose is to save user data from a form in Access to a spreadsheet in Excel, and then use an email client to send an email containing the spreadsheet attachment. The code is as follows
Private Sub Send_Email_Click()
Dim MySheetPath As String
Dim Xl As Excel.Application
Dim XlBook As Excel.Workbook
Dim XlSheet As Excel.Worksheet
' Tell it location of actual Excel file
MySheetPath = "\\SERVER\Users\Public\Documents\WORK ORDERS\Blank Work Order.xlsx"
'Open Excel and the workbook
Set Xl = CreateObject("Excel.Application")
Set XlBook = GetObject(MySheetPath)
'Make sure excel is visible on the screen
Xl.Visible = True
XlBook.Windows(1).Visible = True
'Define the sheet in the Workbook as XlSheet
Set XlSheet = XlBook.Worksheets(1)
'Insert values in the excel sheet starting at specified cell
XlSheet.Range("B6") = Jobnameonform.Value
XlSheet.Range("C7") = Companynameonform.Value
XlSheet.Range("C8") = Employeename.Value
XlSheet.Range("H7") = Jobnumberonform.Value
Xl.ActiveWorkbook.Save
Xl.ActiveWorkbook.Close
Xl.Quit
'in case something goes wrong
Set Xl = Nothing
Set XlBook = Nothing
Set XlSheet = Nothing
Dim cdomsg
Set cdomsg = CreateObject("CDO.message")
With cdomsg.Configuration.Fields
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'NTLM method
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smptserverport") = 587
.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "matthewfeeney6#gmail.com"
.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "REDACTED"
.Update
End With
' build email parts
With cdomsg
.To = "matthewfeeney6#gmail.com"
.From = "matthewfeeney6#gmail.com"
.Subject = "Test email"
.TextBody = "Did you get the attachment?"
.AddAttachment "\\SERVER\Users\Public\Documents\WORK ORDERS\Blank Work Order.xlsx"
.Send
End With
Set cdomsg = Nothing
MsgBox "Completed"
End Sub
Without the line ".AddAttachment..." The code works exactly as intended, minus sending the attachment of course. However, with that line, I get a runtime error 91, with the debugger citing the line "Xl.ActiveWorkbook.Save" as the problematic code. Also, without the code to modify the excel spreadsheet, the simple email portion does work, attachments included. If anyone can provide insight as to why I am getting this error, that would be very helpful. Thanks in advance!
EDIT: Retesting the code, it seems to consistently crash at Xl.ActiveWorkbook.Save I thought it worked before, but I must have been mistaken
You (think you) are saving and closing your workbook with:
Xl.ActiveWorkbook.Save
Xl.ActiveWorkbook.Close
but that's not the workbook you're using and manipulating, which is XlBook:
Set XlBook = GetObject(MySheetPath)
If you save and close the "real" workbook, XlBook:
XlBook.Save
XlBook.Close
then it should work.
The reason you're getting the error at the Save call probably means that the Xl.ActiveWorkbook object doesn't exist/is null or something.

Resources