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
Related
I currently have a string in Microsoft Access that is delegating functions to an external Application.
I have gotten so far as to copying a set of data from the external application.
I want to paste this into an excel workbook that is not open but exists. C:\Users\abcdef\Desktop KDNR.xlsx
how can I integrate this function into my sub procedure?
Thank you in advance
I attempted simply writing
Dim x as Workbook
set x = Workbooks.Open (" workbook name ")
Howoever, i got the compile error "user defined type not defined"
when i just write
Workbooks.Open (" workbook name ")
i get the compile error
"variable not defined"
Use Excel From Access
This is a basic example of how to work with Excel from Access.
It opens a new instance of Excel (whether Excel is open or not), opens the workbook, writes the string Test to cell A1 of worksheet Sheet1, saves and closes the workbook, and finally quits the Excel instance.
' If you haven't already, create a reference to
' "Tools->References->Microsoft Excel 16.0 Object Library"!
Sub Test()
Dim DestinationFilePath As String
DestinationFilePath = Environ("USERPROFILE") & "\DeskTop\KDNR.xlsx"
Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
xlApp.Visible = True ' out-comment when done developing; default is 'False'
Dim wb As Workbook: Set wb = xlApp.Workbooks.Open(DestinationFilePath)
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
ws.Range("A1").Value = "Test"
wb.Close SaveChanges:=True
xlApp.Quit
End Sub
Currently making a quick macro that opens a bunch of other workbooks in new instances:
Sub open_files()
Dim Path As String
Dim Fname As String
Dim xlApp As Object
MyFiles = Dir("C:\my_folder\*xls*")
Do While MyFiles <> ""
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Workbooks.Open ("C:\my_folder\" & MyFiles)
MyFiles = Dir
Loop
End Sub
This works fine on sheets that don't have any ExcelAnt functions in Workbook_Open, but for those that do, I get a popup that says: "Run-time error '1004': cannot run the macro 'Connect'. The macro may not be available in this workbook or all macros may be disabled. "
I've tried forcing in the add-in before running the "connect" part of the code but to no avail.
Public Sub Workbook_Open()
Dim TestWkbk As Workbook
Set TestWkbk = Nothing
On Error Resume Next
Set TestWkbk = Workbooks("ExcelAnt-AddIn64.xll")
On Error GoTo 0
If TestWkbk Is Nothing Then
Set TestWkbk = Workbooks.Open("C:\ExcelAnt\ExcelAnt-AddIn64.xll")
End If
Dim hostenv As String
hostenv = Left(Environ("computername"), 3)
Application.Run "Connect", "prd"
End Sub
To clarify, the sheet if opened manually works fine.
Any help would be appreciated. Thanks in advance.
Use RegisterXLL with the new instance of Excel (xlApp).
xlApp.RegisterXLL "C:\ExcelAnt\ExcelAnt-AddIn64.xll"
I am opening an excel workbook from excel and delete a sheet inside. I want to do this without the message from Excel:
"Excel will permanently delete this sheet, do you want to continue"
However I cannot make the "DisplayAlerts = False" work correctly.
Public Sub xportQuery()
Dim appExcel As Excel.Application
Dim myWorkbook As Excel.Workbook
Dim PathDaily, FileName As String
PathDaily = Forms!Menu!Text69
FileName = Forms!Menu!Text84
Set appExcel = CreateObject("Excel.Application")
Set myWorkbook = appExcel.Workbooks.Open(PathDaily & FileName)
appExcel.Visible = True
'Set appExcel = Nothing
Set myWorkbook = Nothing
appExcel.DisplayAlerts = False
Workbooks(FileName).Sheets("Sheety").Delete
appExcel.DisplayAlerts = True
End Sub
Writing it this way I get a "Subscript out of range" on the Sheets("Sheety").delete
If I take of the two DisplayAlerts lines, the code works but with the alert.
How do I write my code correctly to work without any alert message?
Note: DoCmd.SetWarnings didn t work either as the message is displayed in Excel
Thanks To Sam's Comment:
it works either by changing
Workbooks(FileName).Sheets("Sheety").Delete
into
myWorkbook.Sheets("Sheety").Delete
or
AppExcel.Workbooks(FileName).Sheets("Sheety").Delete
However the rest of the macro can still use Workbooks(Filename) without the "AppExcel." Reference
I'm running a word macro that
initializes Excel
creates a temporary workbook in excel
when exiting the word userform, terminates excel
However, it seems there is some residual Excel instances/workbook that is not fully closed because when I start the word macro again, I get error: 462, remote server machine ...
initialize userform in a word document:
private sub commandbutton1_click()
dim exc as excel.application
set exc as new excel.application
dim wb as excel.workbook
set wb = exc.workbook.saveas filename:="wordexc" 'creates temp workbook
userform1.show
end sub
run excel processing via a userform1 commandbutton:
private sub commandbutton2_click()
excel.workbook("wordexc").close 'closes temp workbook
dim wb as excel.workbook
set wb = excel.workbook.saveas filename:="wordexc" 'this wb is for actual use
'i do not delete this wb after running cuz it has stored data that will be used
'if user cliks commandbutton2 again, it will be deleted and new wbook with new data
'is created
'processing code
end sub
private sub queryclose (etc...)
'Close Excel
Dim sKillExcel As String
sKillExcel = "TASKKILL /F /IM Excel.exe"
Shell sKillExcel, vbHide
end sub
btw i think the problem is the last part:
Dim sKillExcel As String
sKillExcel = "TASKKILL /F /IM Excel.exe"
Shell sKillExcel, vbHide
Cuz if I stop the macro and terminate EXCEL in task manager, it doesn't give me this problem if I run the macro again...
i
I also tried other methods, like calling a excel workbook i saved in a directory instead of a temporary one via createobject("excel.application") in one sub, exc.quit, but I have to use that termination code above cuz otherwise EXCEL still shows in task manager.
Besides not declaring your objects correctly, you are not (if I may say so) flushing the toilet correctly.
See this example (UNTESTED)
I am using Latebinding instead of Early Binding so that this code is compatible with any version of Excel
'~~> Define your Excel objects so that they are available
'~~> in other userform sub procedures as well.
Dim oXLApp As Object, oXLwb As Object
Private Sub CommandButton1_Click()
Set oXLApp = CreateObject("Excel.Application")
'~~> Show Excel
oXLApp.Visible = True
'~~> Add a new workbook
Set oXLwb = oXLApp.Workbooks.Add
'
'~~> Do some stuff
'
'~~> Save the file
oXLwb.SaveAs "C:\wordexc.xlsx", FileFormat:=51
oXLwb.Close SaveChanges:=False
End Sub
'~~> Close and Quit Excel (Flush Toilet)
Private Sub CommandButton2_Click()
oXLApp.Quit
Set oXLwb = Nothing
Set oXLApp = Nothing
End Sub
Why not do something like this? Basically, you define your excel object globally, and then you can call it's "Quit" method later.
Private objExcel As Excel.Application
Private Sub CommandButton1_Click()
Set objExcel = New Excel.Application
objExcel.Visible = True
End Sub
Private Sub CommandButton2_Click()
objExcel.Quit
End Sub
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