Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a variable for an Application name

Tags:

excel

vba

I have a macro that will switch between programs. I've noticed that Excel 2010 and 2016 are named differently in the system (my semantics here are wrong, sorry!) and instead of having to change the code depending on which Excel, I was just thinking I could use a variable to set that.

Sub test()
'code here in Excel

Dim myApp
myApp = Application.Application
AppActivate "Google Chrome"
Call AppActivate("Google Chrome")
' do one or two things

AppActivate myApp
'do more things in Excel
End Sub

Unfortunately, the AppActivate myApp doesn't work. It throws

Run-time Error '5': Invalid procedure call or argument

Is there a way to do what I'm trying? I see on this site that I could do something like:

Public vPID As Variant
vPID = Shell("C:\Windows\system32\notepad.exe", vbNormalFocus)
AppActivate (vPID)

Except, what if Excel isn't located in the same file path on the two computers it's going to be used on?

Edit: It looks like I just need to set the Title of the Application to the variable (again, from that site):

Normally, the AppActivate statement is used to activate an existing application based on its title.

edit2: Getting closer, I found I could get the path to Excel.Exe by this, excelPath = Application.Path & "\Excel.exe" but can't figure out how to call that.

like image 809
BruceWayne Avatar asked May 03 '16 14:05

BruceWayne


People also ask

What are application variables?

Application variables are values that are available to any user or page within an application. For the first time, they can be any value you wish to store.


1 Answers

To activate by the window title of the instance running the code:

AppActivate Application.Caption

Or by Process ID (likely more robust):

AppActivate pid

Where pid is the result of GetCurrentProcessId().

like image 62
Alex K. Avatar answered Sep 27 '22 18:09

Alex K.