VBA. Opening file with its associated application and whose path is stored in a variable

Please help with this.

I don't know why this is not working:

Public Sub OpenFile(ByVal ImagePath As String)    
   Dim WshShell As Object 
   Set WshShell = CreateObject("WScript.Shell")
   WshShell.Run ImagePath    
End Sub

I am getting this exception: (&H80070002)

I am trying to open a file whose path is stored in a variable ImagePath which is a string.

Scenario:

  • ImagePath = "C:\helloWorld.txt"

When I call this function. I want file to be open with its associate software. In this case a text viewer.

If it is a pdf file, I want it to be opened in a pdf viewer.

Files are associated to be opened in their respective application.

Answers


Your code works for me, but if I use whitespaces in the path, I get the same error. To fix this, you path must start and end with " (ex. "C:\youPath"). Change your code to this:

Public Sub OpenFile(ByVal ImagePath As String)    
   Dim WshShell As Object 
   Set WshShell = CreateObject("WScript.Shell")
   WshShell.Run chr(34) & ImagePath & chr(34)    
End Sub

Like I mentioned in the comments above, that error message should popup when the file is not found.

Here is one way to test it.

Const ErrNo = &H80070002

Sub Sample()
    On Error Resume Next
    OpenFile "C:\ImaginaryFile.pdf"

    If Err.Number = ErrNo Then
        MsgBox "File Not Found"
    End If
    On Error GoTo 0
End Sub

Public Sub OpenFile(ByVal ImagePath As String)
   Dim WshShell As Object
   Set WshShell = CreateObject("WScript.Shell")
   WshShell.Run ImagePath
End Sub

Need Your Help

Are “#define new DEBUG_NEW” and “#undef THIS_FILE” etc. actually necessary?

c++ mfc c-preprocessor

When you create a new MFC application, the wizard creates the following block of code in almost every CPP file:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.