AutoNew macro not working - vba

I'm trying to get Word to open an Excel document whenever a document based on a specific template is created.
Here is my macro
Sub AutoNew()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("E:\Letters.xlsx")
End Sub
When I double-click the template, it brings up a document based on the template just fine, but the macro doesn't run.
It shows up in the list of macros in the template, but attempting to run it doesn't do anything.

As has mentioned KazJaw, make app visible
Sub AutoNew()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("E:\Letters.xlsx")
oExcel.Visible = true
End Sub
A disadvantage is, that excel application is launching as a new task (see tak manager) in case of another calling the macro - every document is opened in its own task.
The correct way is use API for launching a document in registered application, for example here: http://access.mvps.org/access/api/api0018.htm
Or one-row workaround, ugly, but works great:
Shell "cmd.exe /c start D:\a\test.xlsx"
Note that template with macro must have extension .xltm, not .xltx.

Related

Powerpoint VBA to switch back to powerpoint from Excel

I hope someone can help....
I have a powerpoint presentation, which has linked tables and graphs from an excel file. the updating of the slides are set to manual.
i have created a VBA code in Powerpoint which opens up the excel file. I am trying to update the links in the powerpoint through VBA instead of manually choosing each linked element and updating the values. while the first part of my VBA code works in opening up the excel file, the links are not being updated, which i think is down to not being back in the powerpoint to update the links, so I am trying to include in my VBA code lines which will go back to the powerpoint presentation, after which i assume the the line to update links will work (happy to be corrected). below is the code i have built so far....my comments are in bold ...
any suggestions?
FYI, I am using office 2007.
Thanks
Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("File location\filename.xlsm", True, False)
Set xlApp = Nothing
Set xlWorkBook = Nothing
Section above opens the excel file which contains the linked tables and charts
On Error Resume Next
With GetObject(, "PowerPoint.Application")
.ActivePresentation.SlideShowWindow.Activate
End With
Section above i was hoping would go back to the powerpoint after opening the excel file but it does not which is why i think the code below to update links is not working
ActivePresentation.UpdateLinks
End Sub
Start from something easier. This will allow you to activate the first existing PowerPoint application from Excel:
Option Explicit
Public Sub TestMe()
Dim ppt As New PowerPoint.Application
ppt.visible = msoTrue
ppt.Windows(1).Activate
End Sub
Then play a bit with it and fix it into your code.
#Vityata
Ok, i got it to work....original coding did the first part of opening the excel file, and to switch back to powerpoint (and i think this will only work if there is only 1 presentation open i added the following code...
AppActivate "Microsoft PowerPoint"
so my complete code looks like:
Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("file path\file name.xlsm", True, False)
Set xlApp = Nothing
Set xlWorkBook = Nothing
AppActivate "Microsoft PowerPoint"
End Sub
now to get manual links to update as part of the vba code...
If you capture the file that your macro is in. This is just a string of your path and filename
'This is the macro file
MacroFile = ActivePresentation.FullName
Then you can use that variable to activate just that specific PowerPoint presentation.
Use Presentations(MacroFile).Activate
or Presentations(MacroFile).Updatelinks
It's best not to use ActivePresentation when moving between applications.

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...

Bypass workbook_open when opening from word

I am working on a project that requires both an excel document and a word document. I have fully programmed the excel document to work using UserForms, one of which opens automatically when opening the document. (see code below)
Private Sub Workbook_Open()
frmOpen.Show
End Sub
The word document has been programmed to read data from this excel document and write it into a report. (see code below)
Private Sub cmdAutomatic_Click()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim selectID As String
Set exWb =objExcel.Workbooks.Open("C:\ Path")
exWb.Close
''Data is written into the document here
Set exWb = Nothing
Unload Me
End Sub
The issue is that every time this button is pressed it opens the user form from the excel document and halts the other code until the user form is closed. Is there a way to only have the User Form open when it.
I have tried
Application.EnableEvents = False
However this just returns a method or data member not found (so I assume that this has to be run excel to excel?)
Sorry if this question has already been answered, I could not find anything that addressed this issue. Also sorry if this has a really simple solution, this is for a school project and this is my first time using VBA
Edit:
I realized that doing the following might work
exWb.Application.EnableEvents = False
However because I need to put this before the "Set" for it to stop the form from opening, it doesnt work (as the object is not set at the point the line is run).
You can disable Excel events with objExcel.EnableEvents = False before opening the workbook and reactivate them afterwards with objExcel.EnableEvents = True.
And as #Siddarth Rout told in comments, you can show your UserForm in Modeless mode with frmOpen.Show vbmodeless to avoid blocking other code execution. See MSDN remarks about this : https://msdn.microsoft.com/en-us/library/office/gg251819.aspx
So your code will look like this :
Private Sub cmdAutomatic_Click()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim selectID As String
objExcel.EnableEvents = False
Set exWb =objExcel.Workbooks.Open("C:\ Path")
exWb.Close
objExcel.EnableEvents = True
''Data is written into the document here
Set exWb = Nothing
Unload Me
End Sub

Excel/VBA: Open New Workbook In New Window

I am using Excel 2010, and am looking for a VBA script that will open a new workbook in a new window (such that I could, for example, place one workbook on each of 2 monitors).
I'd then place this VBA/macro on the ribbon and assign it a shortcut key. Thus, it'd work like CTRL+N, but the new workbook would open in a separate window/instance of Excel, instead of the same.
I've tried just using Shell ("excel.exe"), but I suppose since it is running from my PERSONAL.XLSB workbook, it then asks if I want to Read Only or Notify.
I just want CTRL+N functionality, but with the new window addition.
Thank you!
You can use this:
Sub NewApp()
With CreateObject("Excel.Application")
.Workbooks.Add
.Visible = True
End With
End Sub
but be aware that any automation of this sort won't load startup workbooks and add-ins by default.
Alternate way to do the same thing, includes selecting the file you want to open:
Sub tgr()
Dim strFilePath As String
Dim xlApp As Object
strFilePath = Application.GetOpenFilename("Excel Files, *.xls*")
If strFilePath = "False" Then Exit Sub 'Pressed cancel
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Workbooks.Open strFilePath
End Sub

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