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

Laravel + Eloquent - Passing through custom function first

laravel eloquent

What I want to do is quite simple I think. In my controller I have the code:

PHP Select Form Not Populating: Undefined Index

php html sql select

I am attempting to load some values from my SQL database based on my selected option value. However I am getting the following error.