Home > Net >  Trying to Open a File with a Button from Access using ShellExecute
Trying to Open a File with a Button from Access using ShellExecute

Time:01-23

In my Access database, I have a button on a form to open an external file. Here is the code that I am using for that.

Private Sub btn_OpenFile_Click()
     Dim a As New Shell32.Shell
     Dim strPath As String
     strPath = Me.Attachment
     strPath = Chr(34) & strPath & Chr(34)
     Call a.ShellExecute(Me.Attachment)
     'Call CreateObject("Shell.Application").ShellExecute(strPath)

'MsgBox strPath
End Sub

The problem that I have is if I actually put in the value of the variable (Me.Attachment) it works fine and opens the program and the file.

For Example, If I put in Call a.ShellExecute("C:\Docs\Some File.pdf") it will open. But if I use the variable in it's place it won't open and tells me it cannot find the file. I have verified with the msgbox that it is receiving the correct information. I have tried to wrap it in quotes and have used the Chr(34) as shown above but nothing works.

How can I get that variable to work in the ShellExcute command?

I have looked through all the forums and it seems like everyone is using a string but not a variable. I don't want to use just the shell command as I don't want to track down all of the different apps people use to open different types of files. There will be different file types that will need to be opened and I thought this would be easier than it actually is.

Thank you for the help.

CodePudding user response:

I'm pretty sure that ShellExecute expects a Variant parameter, not a String.

So try this:

Call a.ShellExecute(CVar(strPath))

or use a Variant variable from the start.

I had the same problem here.

CodePudding user response:

Both of the following work for me:

    Dim a As New Shell32.Shell
    Dim strPath As String
    strPath = Me.Attachment
    Call a.ShellExecute(strPath)
    Dim a As Shell
    Dim strPath As String
    strPath = Me.Attachment
    Set a = CreateObject("Shell.Application")
    a.ShellExecute strPath

Even referencing Attachment directly.
a.ShellExecute(Me.Attachment)

  •  Tags:  
  • Related