VBScript code to keep Excel file open - excel

I have a VBScript code to open an excel file, run a macro and close it. Fine.
Now, the only thing I want to change is to leave the file open.
If I remove the 2 lines of code xlApp.activewindow.close and xlApp.Quit, then the workbook and the application are closed anyway, but they remain open in the background (Excel process still active in Task Manager). Hence, it is impossible to re-run the macro later on the same file by calling the script again (which is exactly what I want to do).
Why?
Here is the code:
Option Explicit
On Error Resume Next
MyTest
Sub MyTest()
Dim xlApp
Dim xlBook
Dim fpath
Dim fname
' Excel application running? if not, open Excel
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If xlApp <> "Microsoft Excel" Then
Set xlApp = CreateObject("Excel.Application")
End If
Err.Clear
' correct Excel file open? if not, open it
fpath = "D:\Desktop\"
fname = "MyTest.xls"
xlApp.Workbooks(fname).Activate
If Err = 0 Then
' no error, so it has been possible to activate the workbook
Set xlBook = xlApp.Workbooks(fname)
Else
' unable to activate, so workbook was not open -> open it now
Set xlBook = xlApp.Workbooks.Open(fpath & fname, 0, True)
End If
Err.Clear
' now run the desired macro in the excel file
xlApp.Run "HelloWorld"
' WANT TO CHANGE THIS
xlBook.saved = True
xlApp.activewindow.close
' AND THIS
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub

You just need to make your new instance of Excel visible. Do this right after creating it:
xlApp.Visible = True

This line of code will close your current activated workbook (by now, it is D:\Destop\MyTest.xls);
xlApp.activewindow.close
This line will quit Excel application;
xlApp.Quit

Related

Excel will not fully close after running Word VBA macro

I'm currently trying to make a macro that opens a user defined excel spreadsheet, extracts some data for use in the word document and then closes it. My problem is that when I run the macro, the spreadsheet that I opened is still technically open as a background process in my task manager. I read on another stack overflow question that the reason is because visual basic will not release the reference object from excel until I close out of Microsoft Word. However, even after closing out of Word, the excel background process is still going and I can only stop it by ending the task in the task manager. To clarify, if I run the macro, close Word and then try to open the excel file, I can get in without telling me it's a read only file. However, if I don't close out of Word and I try to go into the spreadsheet after running the macro, then it tells me that it's a read only file. Below is the code I'm using that is causing this problem for me. Thanks to anyone who can help.
Sub UpdateProposal()
'Declares variables
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim SpreadsheetPath As String
Dim xlSheet As Excel.Worksheet
Dim xlRange As Excel.Range
Dim ExcelWasNotRunning As Boolean
Dim ProposalInfoArr(1 To 30) As String
'Skips to ErrorHandler if user cancels out of file dialog
On Error GoTo ErrorHandler
'Display a Dialog Box that allows to select a single file.
'The path for the file picked will be stored in SpreadsheetPath variable
With Application.FileDialog(msoFileDialogFilePicker)
'Makes sure the user can select only one file
.AllowMultiSelect = False
'Filter to just the following types of files to narrow down selection options
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
'Show the dialog box
.Show
'Stores in SpreadsheetPath variable
SpreadsheetPath = .SelectedItems.Item(1)
End With
'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set xlApp = New Excel.Application
End If
'If you want Excel to be visible, you could add the line: xlApp.Visible = True here; but your code will run faster if you don't make it visible
'Open the workbook
Set xlBook = xlApp.Workbooks.Open(FileName:=SpreadsheetPath)
'''Extracts Data
'Quits out of Excel if it was not running previous to running the macro.
If ExcelWasNotRunning Then
xlApp.DisplayAlerts = False
xlApp.Quit
End If
'Make sure you release object references.
Set xlRange = Nothing
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
'Ends the macro before the error handler
Exit Sub
'Ends Macro
ErrorHandler:
MsgBox "The following error occurred: " & Err.Description
End Sub
You are defining the objects correctly:
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlRange As Excel.Range
but you forgot about the implicitly used Workbooks object... as most of the answers you will find do... which means it doesn't get released. So do it like this:
Dim SpreadsheetPath As String
Dim xlApp As Excel.Application
Dim xlBooks As Excel.Workbooks
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlRange As Excel.Range
SpreadsheetPath = "C:\MyPath\MyFile.xlsx"
Set xlApp = New Excel.Application
' Set xlApp = GetObject(, "Excel.Application") ' or attach to an existing one
Set xlBooks = xlApp.Workbooks
Set xlBook = xlBooks.Open(FileName:=SpreadsheetPath) ' you can use .Add instead if someone else may have it open already
Set xlSheet = xlBook.Worksheets(1)
Set xlRange = xlSheet.Range("A1")
' do stuff with the worksheet/range
xlRange.Value = "foo"
' the order matters
' just like it does
' when you create the objects
Set xlRange = Nothing
Set xlSheet = Nothing
xlBook.Close False
Set xlBook = Nothing
Set xlBooks = Nothing
xlApp.Quit
Set xlApp = Nothing
However, you may find that it still isn't getting released when you want, but it will get released when you close the program you are using to create it (in your case, MS-Word) as that is (presumably) when Windows does its built-in garbage collection.
Note: I removed the error handling just to keep it a clean example, but you can leave that in

How to fix closing Excel from inside Access

I want to close an Excel workbook from inside Access using VBA code. The following code opens the workbook and runs a VBA module in the workbook correctly. Closing the workbook prompts with the standard Save dialogue which I want to avoid.
I tried modifying the statement .Workbooks.Close to .Workbooks.Close SaveChanges:=True but that actually crashes the code.
Public Function Open_Share_Price_Excel()
' Change Cursor to Hourglass
Screen.MousePointer = 11
Dim Expath, ModName As String
Dim XLApp As Object
Set XLApp = CreateObject("Excel.Application")
'
'Define where the Excel Spreadsheet is and the module to run
'
Expath = "C:\Users\peter\Documents\Financial Affairs\Shares\Share Price Bing.xlsm"
ModName = "Combined_Module"
With XLApp
.Application.Visible = True
.Application.DisplayAlerts = False
.UserControl = True
.Workbooks.Open Expath
.Run ModName
.Workbooks.Close
End With
XLApp.Quit
Set XLApp = Nothing
'Change Cursor back and display finished message
Screen.MousePointer = 0
MsgBox ("Price Update Finished - OK to Continue")
End Function
I tried modifying the statement .Workbooks.Close to .Workbooks.Close SaveChanges:=True but that actually crashes the code.
Any suggestions welcome.
Secondly, I would like to ensure that I close all the excel workbooks as I understand that the workbook Personal.xlsx may also be open. When I manually close the Excel spreadsheet it closes, but then EXcel immediately re-opens with a blank workbook.
Help this newbie please
What you need to do is to set the opened workbook to a variable Set OpenedWb = .Workbooks.Open(Expath) so you can access exactly that workbook to close it OpenedWb.Close SaveChanges:=True.
.Workbooks.Close does not work because Workbooks repersents all workbooks and not a specific one (but you must close each workbook on its own).
Please note that Dim Expath, ModName As String only declares ModName As String but Expath As Variant. In VBA you need to specify a type for every variable, otherwise it is Variant by default. So you must use: Dim Expath As String, ModName As String to make them both strings.
Your Function does not return anything. Therfore it should be a procedure Sub instead of a function.
You would end up using something like below:
Public Sub Open_Share_Price_Excel()
' Change Cursor to Hourglass
Screen.MousePointer = 11
'
'Define where the Excel Spreadsheet is and the module to run
'
Dim Expath As String
Expath = "C:\Users\peter\Documents\Financial Affairs\Shares\Share Price Bing.xlsm"
Dim ModName As String
ModName = "Combined_Module"
Dim XLApp As Object
Set XLApp = CreateObject("Excel.Application")
With XLApp
.Application.Visible = True
.Application.DisplayAlerts = False
.UserControl = True
Dim OpenedWb As Object
Set OpenedWb = .Workbooks.Open(Expath)
.Run ModName
OpenedWb.Close SaveChanges:=True
End With
XLApp.Quit
Set XLApp = Nothing
'Change Cursor back and display finished message
Screen.MousePointer = 0
MsgBox ("Price Update Finished - OK to Continue")
End Sub

VBA to get open Excel Binary Workbook

I have an MS Access form that opens an Excel binary file (.xlsb) from another website. I am trying to check all the user's open Excel files so that I work on the correct workbook.
By running the loop below on the opened, but not saved Excel file, the GetObject does not find the just opened workbook. This code does find other Excel files that I might already have open.
But, if I save the Excel file that I opened from the network, close and reopen it before I try to find the open Excel files with the code below, the code finds that file too.
Is there a better way for me to capture the just-opened file name? On the new Excel file, I need to filter data from particular Excel tabs and add that data to Access tables.
Dim xlApp As Excel.Application
Dim strWBList As String
strWBList = ""
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number = 0 Then
Dim xlWB As Excel.Workbook
For Each xlWB in xlApp.Workbooks
If Len(strWBList) > 0 Then
strWBList = strWBList & ","
End If
strWBList = strWBList & xlWB.Name
Next xlWB
Set xlApp = Nothing
Set xlWB = Nothing
End If
MsgBox strWBList

How to open Excel if not already open

I'm trying to find a way to open Excel using Outlook VBA, but only if it's not already open. I managed to find some code on the internet that opens Excel, does changes and then closes it, but it doesn't behave nicely if the Excel workbook is already open(it does apply the changes, but it no longer closes the Excel workbook, and it simply leaves it with a grey interior; also, sometimes it doesn't even show in the explorer anymore and I have to close it from the task manager).
I would also greatly appreciate if someone could explain what most of the code does.
Public xlApp As Object
Public xlWB As Object
Public xlSheet As Object
Sub ExportToExcel()
Dim enviro As String
Dim strPath As String
'Get Excel set up
enviro = CStr(Environ("USERPROFILE"))
'the path of the workbook
strPath = enviro & "\Documents\test2.xlsx"
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")
' Process the message record
On Error Resume Next
xlWB.Close 1
If bXStarted Then
xlApp.Quit
End If
End Sub
I know what the xlWb and xlSheet objects do, and how they're declared, and I also understand what the environ function and strPath string do, but I don't undestand why we need the bXStarted boolean, what Set xlApp = GetObject does, why the Application.StatusBar message doesn't get displayed, the difference between GetObject and CreateObjectand why so many error tests are needed.
Thanks in advance.
The difference between get object and create object is in the title, one will get open excel.application, if there is an error err<>0 then it creates an excel.application. I think you'll be getting a saveas message, as the file may not be saving, but open, and you're instructing it to save, the error resume next is skipping it . Try saving before just a .close If you remove the on error resume next the error wont be skipped and will be shown.
Sub explaination()
Dim blnDidICreateExcel As Boolean ' Please read MSDN on boolean
Dim objToHoldExcelCreatedOrNot As Object ' Please read MSDN on objects create/get
' Does the user have Excel open, if i try to get it, then there will be an error logically if not
Set objToHoldExcelCreatedOrNot = GetObject(, "Excel.Application")
' Was there an error
If Err <> 0 Then
' There was, so i need to create one
Set objToHoldExcelCreatedOrNot = CreateObject("Excel.Application")
blnDidICreateExcel = True ' Yes, i created it
End If
' Do the neccessary
' CLose the workbook
' Did i create this Excel, if so tidy up
If blnDidICreateExcel Then objToHoldExcelCreatedOrNot.Quit
End Sub

Reference and access Excel from Outlook

I'm trying to update an Excel file from Outlook (Office 2010). How do I reference and access Excel?
As a simple test I'm trying to count the number of open workbooks. When I run this I get 0, even though there are 2 open.
Sub Test()
Dim xlApp As Excel.Application
Dim xlWBook As Excel.Workbook
Set xlApp = New Excel.Application
Debug.Print "xlApp.Workbooks.Count = " & xlApp.Workbooks.Count
On Error Resume Next
Set xlWBook = xlApp.Workbooks("Data.xlsx")
Err.Clear 'Clear error and open File Index
If xlWBook Is Nothing Then
Set xlWBook = xlApp.Workbooks.Open("C:\Users\Chris\Desktop\Data.xlsx")
End If
End Sub
This is what I use to detect Excel:
Dim xlApp As excel.Application
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number = 429 Then 'Excel not running
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
once xlApp is set, you can use xlApp.Workbooks.Count to count the worksheets
Note: This code will get the first one opened, if there are more than one instance of Excel to find
If you have to find a specific workbook, from this page, Set xlApp = GetObject("Book2").Application will find the workbook, even if it's not in the first instance. If the workbook is from a file, or already saved, replace book2 with the full path and filename - Side effect - this will also open the file if it is not already open
More usage info: http://msdn.microsoft.com/en-us/library/aa164798%28v=office.10%29.aspx

Resources