Quitting Excel Workbook from Word leaves Excel open - vba

I have a Macro in Word, that is reading data from an Excel file.
I have the following lines in my Macro to open and close the Excel file:
Excel_path = "C:\Users\....\Documents\myExcelfile.xlsx"
Dim myExcel As Object
Dim myWB As Object
Set myExcel = CreateObject("Excel.Application")
Set myWB = myExcel.Workbooks.Open(Excel_path)
With myWB.Sheets(2)
*.... Reading in data ....*
End With
myWB.Close savechanges:=False
myExcel.Quit
End Sub
Although I close both the workbook and I quit the application, I keep getting the message that my Excel file is locked for editing after succesfully running the Macro in Word. Also, if I close the Word application I keep having this..
I checked in my Excel workbook, but it doesn't show any connections.
How can I truly quit my Excel workbook?

I would Suggest you to do :
Application.Quit
For example :
myWB.Close SaveChanges:=False
With myExcel
.DisplayAlerts = False
.Quit
End With
And if after that Excel process Still exist in your process manager then use kill to kill excel process. You can found an example there.
Basicly I would do like this to be sure that Excel Is definitivly closed :
Sub Tryme()
Dim MyList As Object
Dim oServ As Object
Dim cProc As Variant
Dim oProc As Object
myWB.Close SaveChanges:=False
With myExcel
.DisplayAlerts = False
.Quit
End With
Set objList = GetObject("winmgmts:") _
.ExecQuery("select * from win32_process where name='" & process & "'")
If MyList.Count > 0 Then
Set oServ = GetObject("winmgmts:")
Set cProc = oServ.ExecQuery("Select * from Win32_Process")
For Each oProc In cProc
If oProc.Name = "EXCEL.EXE" Then
MsgBox "KILL" ' used to display a message for testing pur
oProc.Terminate()
End If
Next
End If
End Sub

Don't close the workbook, instead do:
myWB.Saved = True
myExcel.Quit
Instead of setting .Saved you can also set
myWB.DisplayAlerts = False

Related

Overflow error while opening 2nd Excel

I am looking for help after many hours of research.
My problem is a little bit tricky but...
I am working on new Excel-VBA Applications for my company.
I developped some code to help me to open new instances of Excel everytime I open a new workbook.
My problem comes when i try to open a second Excel while my workbook is already open. I get an un-understandable error 6 Overflow.
There are the tools that I developped to open new Excel instances.
Option Explicit
Private WithEvents ThisExcelApplication As Application
Private WithEvents OtherExcelApplication As Application
Private l_blnSaveNewWorkbook As Boolean
'Procédure : Workbook_Open
'Event : opening workbook
Public Sub Workbook_Open()
Debug.Print Time & " : ThisWorkbook\Workbook_Open()"
If Application.Workbooks.Count > 1 Then
Call ReOpenApplicationInNewExcelInstance
Else
l_blnSaveNewWorkbook = False
End If
Set ThisExcelApplication = Application
Load ufConnection
ufConnection.Show
End Sub
There is my Workbook_open, it checks if there is an existing workbooks opened then it opens my workbook on a new excel instance. But my problem doesn't come from here.
Private Sub ThisExcelApplication_WorkbookOpen(ByVal Wb As Workbook)
Dim strFile As String
If Wb.FullName = ThisWorkbook.FullName Then Exit Sub
Set OtherExcelApplication = CreateObject("Excel.Application")
strFichier = Wb.FullName
Wb.Close False
If g_blnApplicationVisibility Then
ThisExcelApplication.Visible = True
Else
ThisExcelApplication.Visible = False
End If
OtherExcelApplication.Visible = True
OtherExcelApplication.Workbooks.Open strFile
End Sub
Private Sub ReOpenApplicationInNewExcelInstance()
Dim oExcel As Excel.Application
Dim strFiler As String
Dim strTemporaryFileName As String
l_blnSaveNewWorkbook = True
Set oExcel = CreateObject("Excel.Application")
strFile = ThisWorkbook.FullName
strTemporaryFileName = ThisWorkbook.Path & Application.PathSeparator
& "TemporaryFileName.xlsb"
'save current workbook on a temporary file to free the access of original workbook
Application.DisplayAlerts = False
Application.EnableEvents = False
ThisWorkbook.SaveAs strTemporaryFileName
Application.EnableEvents = True
Application.DisplayAlerts = True
'close the original workbook and re-open it on new instance
oExcel.Workbooks.Open strFile
'close the 1rst workbook and kill the temporary files
ThisWorkbook.ChangeFileAccess xlReadOnly
Kill strTemporaryFileName
ThisWorkbook.Close False
End Sub
When I open a second workbook when the 1rst one is already open, the ThisExcelApplication_WorkbookOpen Method is logicaly called. It checks the name of the opened workbooks. If it is not the same name, it tries to open a new excel instance and open this workbook on it.
Then i get the error 6 Overflow on this line :
OtherExcelApplication.Workbooks.Open strFichier
Maybe someone have an idea to help me?
Thanks a lot for your attention.
PS: Sorry for my english, it might be bad !

Ignore "Do you wish to save" box on exit of excel

I have a script that opens an excel file and runs a macro, then quits the file. Since the file is in read only mode, and the script makes temporary changes to the file, when the script calls myExcelWorker.Quit() excel asks if I want to save my changes and I must click 'no'. Is there any way to exit the program and skip this box?
' Create a WshShell to get the current directory
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
' Create an Excel instance
Dim myExcelWorker
Set myExcelWorker = CreateObject("Excel.Application")
myExcelWorker.Visible = True
' Tell Excel what the current working directory is
' (otherwise it can't find the files)
Dim strSaveDefaultPath
Dim strPath
strSaveDefaultPath = myExcelWorker.DefaultFilePath
strPath = WshShell.CurrentDirectory
myExcelWorker.DefaultFilePath = strPath
' Open the Workbook specified on the command-line
Dim oWorkBook
Dim strWorkerWB
strWorkerWB = strPath & "\BugHistogram_v2.xlsm"
Set oWorkBook = myExcelWorker.Workbooks.Open(strWorkerWB)
' Build the macro name with the full path to the workbook
Dim strMacroName
strMacroName = "CreateImagesButton_Click"
on error resume next
' Run the calculation macro
myExcelWorker.Run strMacroName
if err.number <> 0 Then
' Error occurred - just close it down.
End If
err.clear
on error goto 0
' oWorkBook.Save ' this is ignored because it's read only
myExcelWorker.DefaultFilePath = strSaveDefaultPath
' Clean up and shut down
Set oWorkBook = Nothing
' Don’t Quit() Excel if there are other Excel instances
' running, Quit() will
' shut those down also
if myExcelWorker.Workbooks.Count = 0 Then
myExcelWorker.Quit
End If
myExcelWorker.Quit()
Set myExcelWorker = Nothing
Set WshShell = Nothing
ActiveWorkbook.Close False (to close the workbook)
Application.Quit (to quit Excel - doesn't prompt to save changes)
From Microsoft Support's How to suppress "Save Changes" prompt when you close a workbook in Excel:
To force a workbook to close without saving any changes, type the
following code in a Visual Basic module of that workbook:
Sub Auto_Close()
ThisWorkbook.Saved = True
End Sub
Because the Saved property is set to True, Excel responds as though the workbook has already been saved and no changes have
occurred since that last save.
The DisplayAlerts property of the program can be used for the same
purpose. For example, the following macro turns DisplayAlerts off,
closes the active workbook without saving changes, and then turns
DisplayAlerts on again.
Sub CloseBook()
Application.DisplayAlerts = False
ActiveWorkbook.Close
Application.DisplayAlerts = True
End Sub
You can also use the SaveChanges argument of the Close method.
The following macro closes the workbook without saving changes:
Sub CloseBook2()
ActiveWorkbook.Close savechanges:=False
End Sub
The answer you have above is for VBA - you can address this in your VBS directly by using
oWorkBook.Close False
Set oWorkBook = Nothing
in place of
Set oWorkBook = Nothing

Calling VBA macro from .vbs file throws 800A03EC error

I'm trying to run a VBA macro through .VBS file(File name: Check_final.vbs). Here is the code
Option Explicit
run_macro
Sub run_macro()
Dim xl1
Dim sCurPath
Dim xlBook
Dim FolderFromPath
Set xl1 = CreateObject("Excel.application")
sCurPath =Wscript.ScriptFullName
Set xlBook = xl1.Workbooks.Open(sCurPath, 0, True)
xl1.DisplayAlerts = False
FolderFromPath = Left(sCurPath, InStrRev(sCurPath, "\"))
xl1.Application.run FolderFromPath & "Changed_chk.xlsm!Check"
Set xlBook = Nothing
End Sub
When I run this .vbs file I get this popup 'Changed_chk.xlsm is locked for editing' with Read only and notify options. If I acknowledge it with either Read only or notify option a excel sheet is opened in the name of Check_final (which is the file name of that .vbs file) and the above mentioned code is shown written in that excel file. Then I get a Windows script host error(code: 800A03AC) saying macro may not be available or all macro's are disabled.(Though I have enabled the macro as mentioned here.[http://www.addictivetips.com/windows-tips/enable-all-macros-in-excel-2010/)].
Any help on this is much appreciated. Thanks in advance.
You open your vbs-file instead of your excel-file... Also make sure that your function/sub is public. In the example below, I created a Public Sub Check in the module "YourModuleName", which I call from the vbs-file.
Option Explicit
run_macro
Sub run_macro()
Dim xl1
Dim xlBook
Dim FolderFromPath
Set xl1 = CreateObject("Excel.application")
FolderFromPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
set xlBook = xl1.Workbooks.Open(FolderFromPath & "Changed_chk.xlsm")
xl1.Application.run "'" & xlBook.Name & "'!YourModuleName.Check"
xl1.Application.Quit
End Sub
Try this simple code (UNTESTED)
Dim oXlApp, oXLWb, sCurPath
Set oXlApp = CreateObject("Excel.application")
sCurPath = Replace(WScript.ScriptFullName, WScript.ScriptName, "")
Set oXLWb = oXlApp.Workbooks.Open(sCurPath & "Changed_chk.xlsm")
oXlApp.DisplayAlerts = False
oXlApp.Run "Check"
'~~> Close the file here. Save or discard the changes as per your requirement
'oXLWb.Close (True)
'oXLWb.Close (False)
oXLWb.Close
oXlApp.Quit
Set oXLWb = Nothing
Set oXlApp = Nothing
Also where is your macro? In a sheet or in a module? You may want to see THIS
I think there may be something wrong with calling the run_macro statement. From the test i created in excel VBA there is an error if i try to call the sub outside of another sub
Option Explicit
test
Sub test()
MsgBox ("Test")
End Sub
I think you may want to
Option Explicit
Sub Start
run_macro
End Sub
Sub run_macro()
'code here
End Sub
or remove the run_macro line altogether?

Using VB.Net Read from file, edt cells and finally save

Public Function SetInfo(ByRef place As String, ByRef name As String) As Boolean
Dim Completed As Boolean = False
Dim MyExcel As New Excel.Application
Dim myworkbook As New Excel.Workbook
myworkbook = MyExcel.Workbooks.Open(place)
MyExcel.Workbooks.Open(place)
Dim x As Integer
Dim y As Integer
Dim finish As Boolean = False
MyExcel.Sheets("Sheet1").activate()
MyExcel.Range("B1").Activate()
Do
If MyExcel.ActiveCell.Value = name Then
Exit Do
Else
MyExcel.ActiveCell.Offset(0, 1).Activate()
End If
Loop
Do
If MyExcel.ActiveCell.Text = "" Then
MyExcel.ActiveCell.Value = "attended"
MsgBox("Wrote.")
Exit Do
Else
MyExcel.ActiveCell.Offset(1, 0).Activate()
End If
Loop
myworkbook.Save()
MyExcel.Workbooks.Close()
MyExcel = Nothing
Return finish
End Function
I will explain this code.
Start with Cell B1, and whenever the cell doesn't include what I wanted, the activate cell go right.
And if the cell is what I wanted, it goes down until program find blank space.
And in this process, there's no problem.
In saving process, it occurs problem.
If I delete these section
Dim myworkbook As New Excel.Workbook
myworkbook = MyExcel.Workbooks.Open(place)
and
myworkbook.Save()
"Something has been change, will you save it?" this Excel messagebox comes out.
And I don't want to see the messagebox and I want to save it in my program.
What should I do?
PS.Sry for my bad English.
Application.DisplayAlerts = False
myworkbook.Save()
Application.DisplayAlerts = True
Or you can use .saveAs()
msdn: http://msdn.microsoft.com/de-de/library/microsoft.office.tools.excel.workbook.saveas(v=vs.80).aspx
see: Saveas issue Overwrite existing file ( Excel VBA)
Sub Sample()
Dim fName As Object
'~~> Offer user to Save the file at a particular location
fName = Application.GetSaveAsFilename
'~~> Check if it is a valid entry
If fName <> False Then
'~~> Check before hand if the file exists
If Not Dir(fName) <> "" Then
'~~> If not then save it
ActiveWorkbook.SaveAs Filename:=fName
Else
'~~> Trap the error and ignore it
On Error Resume Next
If Err.Number = 1004 Then
On Error GoTo 0
Else '<~~ If user presses Save
ActiveWorkbook.SaveAs(Filename:=fName, _
FileFormat:=xlWorkbook, _
ConflictResolution:=xlLocalSessionChanges)
End If
End If
End If
End Sub

Can't close Excel App with vba in a scheduled task

I have made a code in vba which works with different Workbooks and Worksheets. This code must be execute in a scheduled task. But for an unknow reason I have a problem with it :
When I execute it manually, it works fine and excel closes itself. But with my scheduled task, Excel closes all Workbooks and Worksheets but it stays open.
Here you have my code :
Set xlApp = GetObject(, "excel.application")
Set wkbMe = xlApp.ActiveWorkbook
test = False
xlApp.DisplayAlerts = False
xlApp.AskToUpdateLinks = False
'Open files
xlApp.Workbooks.Open Filename:=MarketDataPath & WbRiskedge, ReadOnly:=True
xlApp.Workbooks.Open Filename:=MarketDataPath & WbMarketData, ReadOnly:=True
Set WorksheetIncoming = xlApp.Workbooks(WbMarketData).Worksheets(wsIncoming)
Set WorksheetMarketdata = xlApp.Workbooks(WbMarketData).Worksheets(WsMarketData)
xlApp.Workbooks.Open Filename:=GTPath & WbGoodTime, ReadOnly:=True
Cells.Copy
WorksheetIncoming.Activate
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks(WbGoodTime).Close
WorksheetMarketdata.Calculate
Worksheets(wsMarketDataForWebsite).Calculate
Worksheets(wsMarketDataForWebsite).Activate
If test = False Then
Application.Run "MarketEnv.xlsm!subCreateCSV"
End If
Workbooks(WbMarketData).Close , False
Workbooks(WbRiskedge).Close , False
xlApp.DisplayAlerts = True
xlApp.AskToUpdateLinks = True
ThisWorkbook.Save
ThisWorkbook.Saved = True
xlApp.Quit
End Sub
I have tried different solutions found on the web but nothing work. Even if I only make :
Set xlApp = GetObject(, "excel.application")
xlApp.Quit
End Sub
my excel stays open.
Anyone can help me plz ?
Okay, this seems long winded... but here goes.
The problem you are seeing is because there can be more than one instance of the Excel Application on a machine at a given time.
When you are manually running the file, you are likely using the default behavior, which is that when you open a workbook directly it opens in your already loaded Excel Application.
This means that when you use:
Set xlApp = GetObject(, "excel.application")
It is actually returning the current Excel.Application.
However, when you load it via the scheduled task, it generates a new Excel.Application in order to handle your task. When it calls the code I quoted it ends up referencing the Excel.Application you already had open (probably).
Since your scheduled workbook is running in a different instance of Excel.Application, when you run xlApp.Quit it only quits that other Excel and not the one actually running the code.
If you want to also close your automated Excel, you will need to add Application.Quit to the end of your sub. Yes, I do mean use both xlApp.Quit AND Application.Quit.
Now technically, you could have more than one Excel Applications open when you load the new one. If you want to close all instances of Excel, the simplest way I know would be to kill all of them via a vbscript call to a program like this which terminates all processes named excel.exe. Note I did not test this on Win 7:
Dim objWMIService, objProcess, colProcess
Dim strComputer, strProcessKill, strFilePath
strComputer = "."
strProcessKill = "'excel.exe'"
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colProcess = objWMIService.ExecQuery _
("Select * from Win32_Process Where Name = " & strProcessKill)
For Each objProcess In colProcess
objProcess.Terminate
Next
WScript.Quit
Edit: I just wanted to add that you can replicate the behavior of the scheduled task manually by doing the following:
Have Excel already open.
Navigate through your start menu and open Excel.
From the new instance of Excel, open your workbook.
OR
Have Excel already open.
Run the following Excel.exe [path of workbook in quotes]
Edit 2:
Due to your request, I've written this short vbscript file that will close all open Excel Applications without upsetting auto-recover. If you also want to avoid any, "Do you want to save ..." alerts uncomment the commented section.
On Error Resume Next
Dim xlApp
Set xlApp = GetObject(, "Excel.Application")
Do While Err.Number <> 429
'For each wb in xlApp.Workbooks
' wb.saved = true
'next
xlApp.Quit
Set xlApp = Nothing
Set xlApp = GetObject(, "Excel.Application")
Loop
Wscript.quit
To run it, just include the following at the end of your Excel VBA.
Shell "wscript.exe [path of .vbs file]"
I can see you have opened more than one workbook instances with your excel application. You need to close all workbook instances to get the plain excel application and than quit it.
try this: (pseudo code)
dim xlApp as Excel.Application
dim wBook as Excel.Workbook
dim wSheet as Excel.Worksheet
Set xlApp = new Excel.Application
Set wBook = xlApp.Workbooks.Add(wb_Path)
Set wSheet = wBook.Sheets(1)
wSheet.Range("A1").Value = "Hello this is a test from vbcode"
wbook.close saveChanges:= true
xlApp.quit
Above code will open your workbook. write a custom message on your worksheet
saves the changes and closes. and the xlapp will also be terminated/destroyed.