How to Browse and Open a PDF File in Visual Basic

Problem:

Create a program that will allow the user to browse and select a pdf file then open the selected file using visual basic 6.

Solution:

To solve the problem above we are going to create a step by step tutorial that will teach us how to browse pdf files in our computer, get the path and open it using Visual Basic 6.

Follow the simple steps:

  1. Open your visual basic 6 program then select Standard EXE.
  2. A new project will be created with a Form1 on it.
  3. We need to add the following control to our form:
    1. 1 label
    2. 1 textbox
    3. 2 command buttons
    4. 1 common dialog

Note: name the textbox into txtpath. Leave the rest of the control to its default name.

  1. Common dialog control is not loaded in the basic component of vb6, we need to add it in the components menu. In the menu bar select Project then Components. A dialog box will appear, in the control tab scroll down, find and check the Microsoft Common Dialog Control 6.0 (SP6). Click OK.

vb6-13-15-1

  1. The design of the form should look like the image below.
    vb6-13-15-2
  2. Next is we’re going to add a Module. Project in the menu bar then select Add Module.
  3. Paste the code below to the newly created module.
Public 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
  1. Back to the form. Double click the browse button and paste the code
With CommonDialog1
.DialogTitle = "Browse PDF"
.Filter = "PDF Files(*.pdf)|*.pdf"
.ShowOpen
txtpath.Text = (CommonDialog1.FileName)
End With

Code Explanation:

The code will allow you to browse pdf files only and display the path of the file in a textbox.

  1. Double click Open PDF button and paste the code
Dim strFile As String
If txtpath.Text = "" Then
MsgBox "Please select a pdf file."
Else
strFile = txtpath.Text
ShellExecute 0&, "open", strFile, "", "", MAXIMIZE
End If

Code Explanation:

The code will open the pdf file using the path of the selected file.

  1. Save the project and Run it (press F5)

Download

Comments

comments

, , , , ,

Post navigation