Archive for the ‘VBA’ Category
VB: Opens Office Documents in Web Browser Control
Use the following steps to create a Visual Basic application that opens Office documents:
- Start Visual Basic and create a new Standard project. Form1 is created by default.
- From the Project menu, select Components to open the Components dialog box.
- In the Components dialog box, add references to the Microsoft Common Dialog Control and the Microsoft Internet Controls.
- Click OK to add the items to the toolbox.
- Add an instance of the WebBrowser control, CommonDialog control, and a CommandButton to Form1.
- 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
- 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.
- Choose Open and the document should open inside the WebBrowser control.
- A message box then appears that displays the name of the Office application that opened the file.

