VB: Opens Office Documents in Web Browser Control

Use the following steps to create a Visual Basic application that opens Office documents:

  1. Start Visual Basic and create a new Standard project. Form1 is created by default.
  2. From the Project menu, select Components to open the Components dialog box.
  3. In the Components dialog box, add references to the Microsoft Common Dialog Control and the Microsoft Internet Controls.
  4. Click OK to add the items to the toolbox.
  5. Add an instance of the WebBrowser control, CommonDialog control, and a CommandButton to Form1.
  6. Next, add the following code into the Code window for Form1:
    Option Explicit
     
    Dim oDocument As Object
     
    Private Sub Command1_Click()
       Dim sFileName As String
     
     ' Find an Office file...
       With CommonDialog1
          .FileName = ""
          .ShowOpen
          sFileName = .FileName
       End With
     
     ' If the user didn't cancel, open the file...
       If Len(sFileName) Then
          Set oDocument = Nothing
          WebBrowser1.Navigate sFileName
       End If
    End Sub
     
    Private Sub Form_Load()
       Command1.Caption = "Browse"
       ' For the 2007 Microsoft Office documents, change the .Filter parameter of the
       ' With CommonDialog1 statement to:
       ' .Filter = "Office Documents " & _
       '      "(*.docx, *.xlsx, *.pptx)|*.docx;*.xlsx;*.pptx"
       With CommonDialog1
          .Filter = "Office Documents " & _
          "(*.doc, *.xls, *.ppt)|*.doc;*.xls;*.ppt"
          .FilterIndex = 1
          .Flags = cdlOFNFileMustExist Or cdlOFNHideReadOnly
       End With
    End Sub
     
    Private Sub Form_Unload(Cancel As Integer)
       Set oDocument = Nothing
    End Sub
     
    Private Sub WebBrowser1_NavigateComplete2(ByVal pDisp As Object, _
    URL As Variant)
       On Error Resume Next
       Set oDocument = pDisp.Document
     
       MsgBox "File opened by: " & oDocument.Application.Name
    End Sub
  7. Press F5 to run the project. When you select the Browse button, the Open dialog box appears allowing you to navigate to a Word, Excel or PowerPoint file.
  8. Choose Open and the document should open inside the WebBrowser control.
  9. A message box then appears that displays the name of the Office application that opened the file.
VN:F [1.8.3_1051]
Rating: 0.0/5 (0 votes cast)
VN:F [1.8.3_1051]
Rating: 0 (from 0 votes)

Tags: , ,

One Response to “VB: Opens Office Documents in Web Browser Control”

  1. [...] This post is related to/same as a previous post VB: Opens Office Documents in Web Browser Control [...]

Get Adobe Flash playerPlugin by wpburn.com wordpress themes