VB6 does not terminate Excel process - excel

I'm having an VB6 application that opens an excel macro enabled file using workbooks.open method. Inside this file, there is an userform that gonna be automatically opened when the file is opened. The problem is the workbooks.open method in vb6 application keeps running and does not jump to next line even when I close my userform (I do have codes to close workbook, quit excel app when the userform is closed). I can only close the interface of my userform but Excel still running in background. As long as I dont close the Excel app in task manager, my vb6 does not terminate excel process and of course it will not jump to next line either.
Here is my code in vb6 to open excel file that contains the userform above
As I said, workbooks.open method works but it does not terminate and keeps the excel app runnning in background
P/s: don't mind the Japanese characters
Private Sub Form_Load()
Dim xlapp
Dim xlwkb
If Not App.PrevInstance Then
Set xlapp = CreateObject("excel.application")
Me.Hide
On Error Resume Next
Set xlwkb = xlapp.workbooks.open("C:\Users\david\Desktop\sale-system\fixedfile.xlsm", Readonly:= True)
Set xlwkb = Nothing
If Not xlapp Is Nothing Then
xlapp.Visible = True
xlapp.Application.quit
Set xlapp = Nothing
End If
Unload Me
Else
MsgBox "プログラムが既に起動されています!", vbInformation, "売上管理システム"
Unload Me
End If
End Sub
Here is my code in excel file when close the userform
Application.DisplayAlerts = False
ThisWorkbook.Close False
Application.Visible = True
Application.Quit
End
I really need to solve this problem in this week, any solution?
Thank you guys in advance and please pardon for my english
Here is some images. I hope they will help you guys to understand my problem
This happens when I use Thisworkbook.close False statement:
This happens when I dont use Thisworkbook.close False statement:

Inside this file, there is an userform that gonna be automatically opened when the file is opened.
when I close my userform (I do have codes to close workbook, quit excel app when the userform is closed).
You are doing this incorrectly. Do not close/quit it from the UserForm. Do it from VB6 form. This way, vb6 will be able to handle and clear the objects.
Here, try this (I already tried it and it works...). This will not leave an instance of Excel running. I have commented the code. But if you still have questions then simply ask.
Note: Before you try this (Just for testing purpose), close all Excel application. Even from the task manager.
Private Sub Form_Load()
Dim oXLApp As Object
Dim oXLWb As Object
Dim ICreateatedExcel As Boolean
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
'~~> I created instance of Excel
ICreateatedExcel = True
End If
Err.Clear
On Error GoTo 0
'~~> Check if you have an instance of Excel
If oXLApp Is Nothing Then
MsgBox "Unable to get an instance of Excel.", vbCritical, "Excel is Installed?"
Exit Sub
End If
Me.Hide
'~~> Show Excel
oXLApp.Visible = True
'~~> Open file
Set oXLWb = oXLApp.Workbooks.Open("C:\Tester.xlsm")
'~~> This and other lines below will not run till the
'~~> time you close the userform in Excel
'~~> Close the workbook
oXLWb.Close (False) '<~~ Set this to True if you want to save changes
Set oXLWb = Nothing
'~~> If I created Excel then quit
If ICreateatedExcel = True Then oXLApp.Quit
Set oXLApp = Nothing
Unload Me
End Sub

Related

Application.Quit closes all open Excel files

I want to close the active macro workbook inside the Userform_Terminate event. The problem I am facing is that, a ghost window of excel application lingers on even after workbook has been closed.
Have tried most of the suggested ways, I could get my hands on (described in detail in the code snippet) but to no avail. If anybody can help, much grateful.
NOTE: Have released almost all excel related objects from memory by setting it to nothing.
Code :
Private Sub UserForm_Terminate()
' Application.DisplayAlerts = False ' The excel ghost window lingers on
' ThisWorkbook.Close , False
' Application.DisplayAlerts = True
'
' Application.DisplayAlerts = False ' The excel ghost window lingers on
' ThisWorkbook.Saved = True
' ThisWorkbook.Close , False
' Application.DisplayAlerts = True
' Application.DisplayAlerts = False 'The excel ghost window lingers on.
' ThisWorkbook.Close , False
' Application.Quit
' Application.DisplayAlerts = True
Application.DisplayAlerts = False 'Ghost window is closed but also kills all instances of excel currently open
Application.Quit
Application.DisplayAlerts = True
'NOTE:
'Have released all excel related objects from memory by setting it to nothing, post use.
End Sub
Snap:
Well, your "gost" problem has the next explanation:
An Excel session/instance means the same Application handler. If you open a workbook from the Excel existing interface, it is open in the same instance. Pressing Ctrl + F6 will jump to the next workbook open in the same instance...
If there are open workbooks not seen in the Ctrl + F6 sequence, this only means that they are open in a different instance.
Another instance is open, for instance :), in this way:
Din ExApp as Object
Set ExApp = CreateObject("Excel.Application")
ExApp.Workbooks.add 'without this line, the instance is quit by itself...
Set ExApp = Nothing 'this only releases the memory
You can see more open Excel instances (if they exist) looking in TaskManager and seeing more the one such application (Excel.exe)...
When you close a workbook, and this specific workbook is the single one of the instance, the application Window, what you name a "gost" remains!. If there are some other workbooks open, the so named "gost" window disappears, too.
In order to handle both situations, please try the next approach:
Private Sub UserForm_Terminate()
If Workbooks.Count > OpenWb Then
ThisWorkbook.Close , False
Else
Application.Quit
End If
End Sub
Function OpenWb() As Long
Dim count As Long, wb As Workbook, arr
For Each wb In Workbooks
arr = Split(wb.Name, ".")
If UCase(arr(UBound(arr))) = "XLSB" Then count = count + 1
Next
OpenWb = count + 1
End Function
Quitting the application is done here only because you asked for it... When you try programmatically to open and close many workbooks, it is more efficient to keep the application open. To open a new instance takes time. To open a workbook in an existing instance takes less time... But to do that, your code must find that existing instance:
Sub testExcelInstance()
Dim Ex As Object
On Error Resume Next
Set Ex = GetObject(, "Excel.Application")
If Ex Is Nothing Then
Err.Clear: On Error GoTo 0
Set Ex = CreateObject("Excel.Application")
End If
On Error GoTo 0
Ex.Workbooks.Add 'just doing something after having the Excel instance object
End Sub
Releasing the objects from the memory does not do anything, in terms of the object itself existence. If physically disappears only if you quit it.

Run Excel Macro from Access macro in VBA

I am trying to run an excel macro from access 2016. This has a lot of examples out their however they are all old. The exact error code I receive is run-time error '1004':
cannot run the macro "TestScript()". The macro may not be available in this workbook or all macros may be displayed. I am only running something easy for the test. I have ensured that macros is enabled in excel. the excel code is as follows
Public Sub TestScript()
MsgBox "IT WORKED"
End Sub
Real simple for the test. Access is opening the excel spreadsheet however it stops there with an error code.
My Access code is very simple and is below. I have also noted where the code stops. While I am new at VBA I have done a lot of research in this. I am testing as simple code as I could figure out. Any help would be welcomed.
Option Compare Database
Function runExcelmacro()
Dim XL As Object
Set XL = CreateObject("Excel.Application")
With XL
'Turn Off warnings
.Visible = False
.displayalerts = False
'WorkBook path such as "C:\Computer\WorkBook.xlsx"
.Workbooks.Open "C:\DATABASE\BLQ-10\Import Database BLQ 10\NTIRAINSTALLTO.xlsm"
'Run the Macro in excel getworkbook
.Run TestScript 'Code stops here!
'Close Workbook
.ActiveWorkbook.Close (True)
.Quite
End With
Set XL = Nothing
End Function
Public Sub runMacroSub()
Call runExcelmacro("C:\DATABASE\BLQ-10\Import Database BLQ 10\NTIRAINSTALLTO.xlsm", "TestScript")
End Sub
I guess OP did not put the code of Testscript in an extra module. Instead the code was put into the class module of the workbook or a worksheet. In the latter case you have to add the workbook or worksheet name in front of the name of the script.
Either it is `
.Run "ThisWorkbook.TestScript"
or in case it is in Sheet1 (codename of the sheet!)
.Run "Sheet1.TestScript"
Do not forget the quotation marks!
PS The OP's code above is working if you put testscript into a module and add quotation marks.
.Run "TestScript"
Here is a description how to create a module and add code
Here try this:
Public Sub TestScript()
MsgBox "IT WORKED"
End Sub
Option Compare Database
Function runExcelmacro()
Dim XL As Object, wb as object
Set XL = CreateObject("Excel.Application")
With XL
.Visible = False
.displayalerts = False
set wb = .Workbooks.Open "C:\DATABASE\BLQ-10\Import Database BLQ 10\NTIRAINSTALLTO.xlsm"
wb.Run TestScript 'Code stops here!
.ActiveWorkbook.Close (True)
.Quite
End With
Set XL = Nothing
End Function
Public Sub runMacroSub()
Call runExcelmacro("C:\DATABASE\BLQ-10\Import Database BLQ 10\NTIRAINSTALLTO.xlsm", "TestScript")
End Sub
Here i declared wb as an object and then set wb = to the workbook.
This is of course assumin your test script is in the actual workbook being opened. Would be real funny if that wasnt a thing lol

How to exit gracefully closing open excel file on error?

I use dos .bat file to run a .vbs file continuously ... If any error occurs the batch file runs the vbscript again and it goes on. The script connects via internet to a site to execute some api calls.
Now when there is connection problem or any other error then the control comes out of the script keeping the excel file open. This way many excel files gets open on each error ... The code is as follows ... please advice me how to close the excel file on error and then come out of the script gracefully.
'{{{{Some coding}}}}
dim objExcel, objWorkbook, objRange
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\temp.xlsx")
objExcel.Visible = True
'{{{{Some coding}}}}
objExcel.Cells(xlrow, 3).Value="Test"
objExcel.Cells(xlrow, 3).Select
objExcel.Activecell.Show
'{{{{Some coding}}}}
objExcel.Workbooks(1).save
objExcel.Workbooks(1).close
objExcel.Quit
Set objExcel = Nothing
Set objWorkbook = Nothing
WScript.Quit
Thanks in advance
One possible approach is to wrap the Excel handling in a custom class:
Class Excel
Private xl
Private Sub Class_Initialize
Set xl = CreateObject("Excel.Application")
End Sub
Private Sub Class_Terminate
For Each wb In xl.Workbooks
wb.Saved = True 'discard unsaved changes
wb.Close 'close workbook
Next
xl.Quit 'quit Excel
End Sub
Public Function OpenWorkbook(filename)
Set OpenWorkbook = xl.Workbooks.Open(filename)
End Function
Public Function NewWorkbook
Set NewWorkbook = xl.Workbooks.Add
End Function
Public Property Get Workbooks
Set Workbooks = xl.Workbooks
End Property
End Class
The procedure Class_Terminate is automatically called whenever a class instance is destroyed. That way you can automatically close the open workbooks and quit Excel.
The class can be used like this:
Set xl = New Excel
Set wb = xl.OpenWorkbook("C:\path\to\your.xlsx")
...
wb.Close

Error Occurring Trying to Close Workbook Exported with Access VBA

I'm trying to write code to have Access close a spreadsheet in Excel that Access just exported. However, I keep throwing an error that tells me my table does not exist even though I'm STARING STRAIGHT AT IT! Very frustrating. All help is greatly appreciated. Thanks.
Private Sub Command12_Click()
DoCmd.SetWarnings False
Const xlFileName As String = "\\ct13nt003\mfg\SMT_Schedule_Files\SMT Line Progress Files\Test\SMT2Updated.xlsx"
Dim xlapp As Object
Dim wb As Object
Set xlapp = CreateObject("Excel.Application")
Set wb = xlapp.workbooks.Open(xlFileName)
'Delete Existing File First; then create new
On Error Resume Next
Kill xlFileName
On Error GoTo 0
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "SMT4Export", xlFileName, True
wb.Close savechanges:=False
Set wb = Nothing
Set xlapp = Nothing
DoCmd.SetWarnings True
End Sub
You open xlFileName in Excel. Then you attempt Kill xlFileName while that workbook file is still open in Excel. So the Kill attempt fails, but you are unaware of that fact because you suppressed the error message by using On Error Resume Next.
You need to close the workbook in Excel to release the lock if you want to Kill it. On the other hand, as Gord already mentioned, there is no indication in your code as to why it's useful to open the workbook in Excel in the first place.
Regarding the error message "Run-time error '3001' - The Microsoft Office Access database engine could not find the object 'SMT4Export'. Make sure the object exists ...", make sure your database includes a table or query named SMT4Export.
It seems TransferSpreadsheet is the goal. I suggest you avoid creating an Excel application instance for now and see whether you can get this simplified version of your code to work ...
Private Sub Command12_Click()
Const xlFileName As String = "\\ct13nt003\mfg\SMT_Schedule_Files\SMT Line Progress Files\Test\SMT2Updated.xlsx"
DoCmd.SetWarnings True
If Len(Dir(xlFileName)) > 0 Then
Kill xlFileName
End If
DoCmd.TransferSpreadsheet acExport, _
acSpreadsheetTypeExcel12Xml, "SMT4Export", xlFileName, True
End Sub

VBScript code to keep Excel file open

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

Resources