Access 2007 VBA - Open Two Excel Workbooks - vba

I am using Access 2007. In my Access file I have VBA code that opens an Excel
workbook when the Access program begins. The Excel workbook remains open
while the program is running. I use this code to open the workbook:
Public xl As Object
Public wb1 As Object
Set xl = New Excel.Application
Set wb1 = xl.Workbooks.Open("c:\Book1.xlsx")
Now while the program is running I may need to open a second Excel workbook,
get some data from it, then close it. I used this code:
Public wb2 As Object
Set wb2 = xl.Workbooks.Open("c:\Book2.xlsx")
But this doesn't work. It seems that the first workbook may have closed because
if I do debug.print Workbooks.Count the response is "0".
Any suggestions on how to open a second workbook and still have the first workbook open?
Should I create a second instance of Excel and use that to open the second workbook?
Thank you.

You may have more luck with this procedure instead:
Sub OpenExcel(fName As String)
Dim xlApp As Object
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
'Excel wasn't running, start it from code
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
xlApp.Workbooks.Open (fName)
End Sub
With your code it's possible that Excel was opening but the second workbook did not default to visible, which could be set with xl.Visible = True. Alternatively, a second xl object could have helped.
Regardless, this method is safer is a number of ways.
Make sure when you're done, make sure you clean up (and free up memory) with something like xlApp.Quit and Set xlApp = Nothing.
In fact, I'd suggest you reboot right now... before you do, take a look at the running processes in your Task Manager - I wouldn't be surprised if you have several "invisible" instances of Excel running. :)

Related

Powerpoint VBA dont close Excel

My VBA code in Powerpoint wont "kill" my excel application.
it still runs if i have a look in task manager.
I would like to close it the right way rather than kill.
Anyone that could help me? I already searched and tried to get it working but with no luck.
Public Sub OnSlideShowPageChange(ByVal Wn As SlideShowWindow)
If Wn.View.CurrentShowPosition = 2 Then
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
Set xlWorkBook = xlApp.Workbooks.Open("D:\ELE_powerpoint\book1.xlsx", True, False)
With xlWorkBook.ActiveSheet
txt1 = xlWorkBook.sheets(1).Range("A2")
txt2 = xlWorkBook.sheets(1).Range("A3")
txt3 = xlWorkBook.sheets(1).Range("A4")
End With
ActivePresentation.Slides(2).Shapes("a2").TextFrame.TextRange = txt1
ActivePresentation.Slides(2).Shapes("a3").TextFrame.TextRange = txt2
ActivePresentation.Slides(2).Shapes("a4").TextFrame.TextRange = txt3
Set xlApp = Nothing
Set xlWorkBook = Nothing
End If
End Sub
Try xlApp.Quit before Set xlApp = Nothing
Set xlApp = Nothing
That instruction sets the xlApp object reference to Nothing. It doesn't destroy the object it's referring to, but it prevents further code from using that reference.
Excel is a rather complex application; creating an instance of an Excel.Application object has many implications, and in order to properly shut itself down, it needs to run through a certain sequence of instructions (unload Excel and COM add-ins, close any opened file, tear down the VBE if it was initialized - which in turn may need to tear down its own add-ins, etc.) - by setting your reference to Nothing, you say "I don't need it anymore" - but what of the COM add-ins that still use it? That workbook that's still open is a Workbook object with an Application property that also references the very same object you were referring to - and these references aren't gone yet!
As Tim and Tom said, you need to call the Quit method of the Excel.Application instance, so that it can clean itself up.
And if that's the last thing your code does, then you probably don't even need to Set xlApp = Nothing, since the VBA runtime will know that it doesn't need to hold on to the xlApp reference after it's out of scope; Set xlWorkbook = Nothing is superfluous as well.
Quitting Excel will close the unmodified workbook you've opened, but since you opened it, I'd argue that it's good form to close it yourself - just call xlWorkbook.Close before you call xlApp.Quit.

Open another workbook with vba that contains all the macros

Instead of having all the macro's stored in each workbook, we would like to have them stored in one global one. We tried using Personal.xlsb file, however every time excel crashes or system administrator forced restart with excel open it created personal.v.01 ....v.100 files, and they interfered with each other, got corrupted etc.. So instead we are trying to add a small macro to each excel workbook we make which then should open a global excel workbook with all the macros, however it does not open it(normal.xlsb), where is the problem? If I manually run it it works fine, it just does not autorun..
Option Explicit
Public Sub Workbook_Open()
Dim sFullName As String
Dim xlApp As Excel.Application
Dim wbReturn As Workbook
sFullName = "Z:\Dokumentstyring\normal.xlsb"
Set xlApp = GetObject(, "Excel.Application") 'need to do so to open it in same instance otherwise the global macros can not be called.
Set wbReturn = xlApp.Workbooks.Open(filename:=sFullName, ReadOnly:=True)
If wbReturn Is Nothing Then
MsgBox "Failed to open workbook, maybe z drive is down?"
Else
ThisWorkbook.Activate'Dont know how to pass object to modules, so instead activate it and in createbutton set wb= activeworkbook..
Application.Run ("normal.xlsb!CreateButtons")
End If
End Sub
Public Sub Workbook_BeforeClose(Cancel As Boolean)
Dim wb As Workbook
For Each wb In Application.Workbooks
If InStr(UCase(wb.Name), "PARTSLIST") > 0 And wb.Name <> ThisWorkbook.Name Then Exit Sub
Next wb
On Error Resume Next
Workbooks("normal.xlsb").Close
Workbooks("filter.xlsx").Close
End Sub
You create your addin, as just an empty workbook, holding nothing but the code
Like this
Then you add a reference to it, in the workbook that you wish to use, in VBA, like this. My Documents, is a folder on a network drive, not "my documents" local.
And then you can call like so.
So based on input from #Nathan_Sav and #Ralph I have come to a partly good solution:
I have called my addinn Normal and saved this on Z:Dokumenstyring\Normal.xlam
I then removed all the code in Thisworkbook of Normal:
Private Sub Workbook_Open()
Dim ExcelArgs As String
Dim arg As String
ExcelArgs = Environ("ExcelArgs")
'Call deleteMacros.deletePersonalFiles
'MsgBox ExcelArgs
If InStr(UCase(ExcelArgs), "CREO,") > 0 Then
Application.DisplayAlerts = False
If Len(ExcelArgs) > Len("CREO,") Then
arg = Split(ExcelArgs, ",")(1)
Call Creo.addNewPartToPartslist(arg)
End If
Application.DisplayAlerts = True
End If
If InStr(UCase(ExcelArgs), "DOKLIST,") > 0 Then
Application.DisplayAlerts = False
If Len(ExcelArgs) > Len("DOKLIST,") Then
arg = Split(ExcelArgs, ",")(1)
Call ProsjektListen.dbDumpDocOut(arg)
End If
Application.DisplayAlerts = True
End If
and put this in a new workbook called Z:Dokumenstyring\Creo.xlsm
I have so edited all my bat files(which previously were using personal.xlsb):
echo "Launch excel"
Set ExcelArgs=CREO,ADDPART
"C:\Program Files (x86)\Microsoft Office\OFFICE16\Excel.exe" /x /r "z:\Dokumentstyring\Creo.xlsm"
So when I run the bat file it adds a parameter to enviroment, start creo.xlsm, which then starts the addin which launch my userform.
So if I now want to update the look of that that userform I do this by modifying the Z:Dokumenstyring\NormalDebug.xlam, then i save a copy which i write over Z:Dokumenstyring\Normal.xlam and I also told every user to not copy the addin to the default location in excel but keep it in Z:Dokumenstyring\Normal.xlam.
My shapes in my excel sheets seems to work with just the macro name in the procedure, however there might be an conflict if two procedures have the same name, but located in different procedures. So I also altered this to
ws1.Shapes(tempName).OnAction = "Normal.xlam!Custom_Button_Click"
However every click starts a new instance of the addin, how to avoid this?

VBA run code in another instance of excel and detach

I currently have the below code which opens a workbook in a new instance of excel (The workbook that is opened has an on open macro).
However when the code is running in the new instance, this also takes up the existing instance of excel and only frees it once the workbook open macro has run.Is there a way to open excel in a new instance and detach/stop the code from the existing workbook immediately?
Please see code below.
Sub OpenWBInNewInstance()
Dim xApp As Excel.Application
Set xApp = New Excel.Application
xApp.Visible = True
Dim wb As Excel.Workbook
Set wb = xApp.Workbooks.Open("Z:\MI\Not Purchased Detail\Not Purchased Detail Disposal Marketing Template.xlsb")
End Sub
Code execution runs on a single thread in VBA, so you can't do what you're asking because the execution won't move to the next line until the entire Workbooks.Open line has been processed - which includes the Workbook_Open event in the other workbook.
A possible workaround it to use VBScript instead:
Sub OpenWBInNewInstance()
Open Environ$("USERPROFILE") & "\Desktop\temp.vbs" For Output As #1
Print #1, "Set xl = CreateObject(""Excel.Application"")"
Print #1, "xl.Workbooks.Open ""Z:\MI\Not Purchased Detail\Not Purchased Detail Disposal Marketing Template.xlsb"""
Close #1
Shell Environ$("USERPROFILE") & "\Desktop\temp.vbs"
'// You will need some kind of hook here to set the workbook in other instance...

VBA on new Excel file

I receive reports almost daily in spreadsheet form. I have a macro code that will take out certain portions of the spreadsheet and put it into a new spreadsheet.
I want to know if there's a way to run that macro without having to manually copy paste it into each new file I receive.
Sub CopyItOver()
Dim newbook As Workbook
Set newbook = Workbooks.Add
ThisWorkbook.Worksheets("sheet1").Range("fe1:fh1").Copy Destination:=newbook.Worksheets("Sheet1").Range("A1:D1")
ThisWorkbook.Worksheets("sheet1").Range("IZ1:JI1").Copy Destination:=newbook.Worksheets("Sheet1").Range("E1")
ThisWorkbook.Worksheets("sheet1").Range("JK1:JL1").Copy Destination:=newbook.Worksheets("Sheet1").Range("O1")
ThisWorkbook.Worksheets("sheet1").Range("KA1:KJ1, Kl1, KR1, KT1").Copy Destination:=newbook.Worksheets("Sheet1").Range("Q1")
ThisWorkbook.Worksheets("sheet1").Range("fe328:fh328").Copy Destination:=newbook.Worksheets("Sheet1").Range("A2")
ThisWorkbook.Worksheets("sheet1").Range("IZ328:JI711").Copy Destination:=newbook.Worksheets("Sheet1").Range("E2")
ThisWorkbook.Worksheets("sheet1").Range("JK328:JL711").Copy Destination:=newbook.Worksheets("Sheet1").Range("O2")
ThisWorkbook.Worksheets("sheet1").Range("KA328:KJ711, KL328:KL711, KR328:KR711, KT328:KT711").Copy Destination:=newbook.Worksheets("Sheet1").Range("Q2")
Columns("E").ColumnWidth = 15
Columns("Q").ColumnWidth = 15
End Sub
When you create a macro and select the option to save to your personal macro workbook it is available every time you start Excel. Or create a custom toolbar button and attach the macro to it, it will always be there...
You can create small .vbs file which you can run (by double click) and it will run your macro automatically on your spreadsheet.
First of all export your working macro to some location. And then copy paste below lines in a text file and save it as .vbs file.
Dim fso, xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
Set xlBook = xlApp.Workbooks.Open(fileToUse)
xlApp.VBE.ActiveVBProject.VBComponents.Import "Path to your .bas file"
xlApp.Run "Name of your Sub"
xlBook.Save
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
Set fso = Nothing
Just change the path in the file.
Like schwack said, you can put the macro in your personal macro workbook and it will always be available, or put it in a workbook that you have open alongside the report workbooks you are receiving. But you will need to change the macro code so it doesn't use the 'ThisWorkbook' object. You could simply use 'ActiveWorkbook' instead.

Is it possible to run a macro in Excel from external command?

Let's say I want to program a VBA code in an external program that opens an Excel file, runs a macro, saves (and say yes to any pop up windows), and close Excel. Is it possible to do so? If so, how would I go about implementing it?
You can launch Excel, open a workbook and then manipulate the workbook from a VBScript file.
Copy the code below into Notepad.
Update the 'MyWorkbook.xls' and 'Sheet1' parameters.
Save it with a vbs extension and run it.
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\MyWorkbook.xls")
xlBook.Sheets("Sheet1").Cells(1, 1).Value = "My text"
xlBook.Sheets("Sheet1").Cells(1, 1).Font.Bold = TRUE
xlBook.Sheets("Sheet1").Cells(1, 1).Interior.ColorIndex = 6
xlBook.Save
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
This code above launches Excel opens a workbook, enters a value in cell A1, makes it bold and changes the colour of the cell. The workbook is then saved and closed. Excel is then closed.
Depending on what you are trying to achieve you may also 'control' Excel via (OLE) Automation from another application such as Access or Word or from your own application written in another environment such as Visual Basic (6). It is also possible to achieve this via .Net using a language of your choice (although some are easier to implement than others).
Are you wanting to control Excel from an external application or simply trigger a VBA macro in an existing workbook from the outside?
Again, depending on your intention, the workbook could have an Auto Open macro which could be conditional run based on an external value (say an ini file or database value).
I can think of several ways to do this.
You can start excel by creating a file with NotePad or a similar text editor.
Here are some steps:
Launch NotePad
Add the following line of text. Replace test.xlsm with the name and path for your file:
start Excel.exe "C\test.xlsm"
Save the file as "Test.bat".
Run the batch file.
The batch file should launch Excel and then open your file. The code in your workbook should run
OR
Again, using Notepad.
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\MyWorkbook.xls", 0, True)
xlApp.Run "MyMacro"
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
Or, this.
'Code should be placed in a .vbs file
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'C:\Users\Ryan\Desktop\Sales.xlsm'!SalesModule.SalesTotal"
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
Now, this isn't 'an external command', but the Windows Task Scheduler will do a nice job of opening that file for you, and once it is opened, you can run a tiny script like the one you see below.
Private Sub Workbook_Open()
Call CommandButton1_Click
End Sub
https://www.sevenforums.com/tutorials/11949-elevated-program-shortcut-without-uac-prompt-create.html