VBA to open Excel or/and Word Files

浪子不回头ぞ 提交于 2020-07-08 03:07:01

问题


I'm trying to setup a command button in a user form to allow the user to open either an Excel and/or a Word Document one at a time or both at the same time. But so far I'm able only to select and open Excel but not Word files with the following code:

Sub OpeningExcelFile()
    Dim Finfo As String
    Dim FilterIndex As Integer
    Dim Title As String
    Dim Filename As Variant
    Dim wb As Workbook


    'Setup the list of file filters
    Finfo = "Excel Files (*.xlsx),*xlsx," & _
            "Macro-Enable Worksheet (*.xlsm),*xlsm," & _
            "Word Files (*.docx),*.docx," & _
            "All Files (*.*),*.*"
             MultiSelect = True


    'Display *.* by default
    FilterIndex = 4

    'Set the dialog box caption
    Title = "Select a File to Open"

    'Get the Filename
    Filename = Application.GetOpenFilename(Finfo, _
        FilterIndex, Title)

    'Handle return info from dialog box
    If Filename = False Then
        MsgBox "No file was selected."
    Else
        MsgBox "You selected " & Filename

    End If

    On Error Resume Next

    Set wb = Workbooks.Open(Filename)

Do you know what it is missing?


回答1:


You cannot open word files with Excel Application.

You need to have check like below to handle this.

Dim objWdApp As Object
Dim objWdDoc As Object
If InStr(1, Filename, ".docx", vbTextCompare) > 0 Then
    Set objWdApp = CreateObject("Word.Application")
    objWdApp.Visible = True
    Set objWdDoc = objWdApp.Documents.Open(Filename) '\\ Open Word Document
Else
    Set wb = Workbooks.Open(Filename) '\\ Open Excel Spreadsheet
End If


来源:https://stackoverflow.com/questions/47321478/vba-to-open-excel-or-and-word-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!