VBA - opening files with Shell command

E

Eric

I'm writing a macro in Excel which finds other files (not Excel files)
with a given name and then opens them. I'm using the Windows registry
to find the programs associated with the files and then using the Shell

command to open the files with the given program. My problem is that
for some programs the Shell command opens a new instance of the program

for each additional file, i.e. each AutoCAD file opens into its own
instance of AutoCAD even if AutoCAD is already running.


So my question is, is there a switch for the Shell command that tells
it to check to see if an instance of a program is already running
before starting a new one, and, if the program is already running,
opens the file with the existing instance? Or is there another way of
doing this without getting into the API of each program in question?


Here's a snippet of my code:


strCmd = appWord.System.PrivateProfileString("", _
"HKEY_CLASSES_ROOT\" & regType & "\shell\Open\command", _
"")


If Len(strCmd) > 0 Then
strCmd = Replace(strCmd, "%1", fileWithPath) 'for pdf & dwg files
strCmd = Replace(strCmd, "/dde", "/one " & """" & fileWithPath &
"""") 'for solidworks files
Shell strCmd, vbNormalFocus
Else
MsgBox prompt:="Could not find an application" & vbCr & _
"registered to display file.", _
Buttons:=vbCritical + vbOKOnly, _
Title:="Not Registered"
End If


Thanks!
Eric
 
J

Jezebel

No, Shell() won't do this for you. In some cases you can use GetObject() to
retrieve the existing instance if any.
 
J

Jonathan West

Hi Eric

You can use the ShellExecute Windows API call for this. Put the following
into a separate module

Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" _
(ByVal hWnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long

Public Function OpenDoc(ByVal DocFile As String) As Long
OpenDoc = ShellExecute(0&, "open", DocFile, vbNullString, vbNullString,
vbNormalFocus)
End Function

Simply call OpenDoc passing the full pathname of the file.


--
Regards
Jonathan West - Word MVP
www.intelligentdocuments.co.uk
Please reply to the newsgroup
Keep your VBA code safe, sign the ClassicVB petition www.classicvb.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top