Classic VB - How do I open a file/web-page in its default application?
To perform either of these tasks you can use the ShellExecute API function as shown below.
ShellExecute basically tells Windows to open the item as if you had double-clicked it in Windows Explorer.
VB Code:
'in General-Declarations:
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
'Example code:
'open a file
ShellExecute Me.hWnd, "open", "c:\My folder\Test.doc", vbNullString, "C:\", ByVal 1&
'open a web page
ShellExecute Me.hWnd, "open", "http://www.VBForums.com", vbNullString, "C:\", ByVal 1&
Here are two useful Subs for you, which will make the code easier to write:
VB Code:
Private Sub OpenAFile(strFileLocation As String)
'Just call the OpenAFile sub with the path of the file to open as its parameter.
If Dir$(strFileLocation) = "" Then
Exit Sub
End If
ShellExecute Me.hWnd, "open", strFileLocation, vbNullString, "C:\", ByVal 1&
End Sub
Private Sub OpenURL(strURL As String)
'Just call the OpenURL sub with the URL of the webpage to open as its parameter.
ShellExecute Me.hWnd, "open", strURL, vbNullString, "C:\", ByVal 1&
End Sub
'Example code (same effect as the examples above)
Call OpenURL("http://www.VBForums.com")
Call OpenAFile("c:\My folder\Test.doc")
:)
Cheers,
RyanJ