VBA打开Excel或/和Word文件

时间:2017-11-16 04:12:19

标签: vba excel-vba excel

我尝试在用户表单中设置命令按钮,以允许用户一次打开一个Excel和/或Word文档,或同时打开两个。但到目前为止,我只能选择并打开Excel,而不能使用以下代码打开Word文件:

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)

你知道它缺少什么吗?

1 个答案:

答案 0 :(得分:0)

您无法使用Excel Application打开Word文件。

您需要按照以下方式进行检查才能解决此问题。

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