简体   繁体   English

VBA打开Excel或/和Word文件

[英]VBA to open Excel or/and Word Files

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. 我正在尝试在用户表单中设置命令按钮,以允许用户一次打开Excel和/或Word文档,或者一次打开两者。 But so far I'm able only to select and open Excel but not Word files with the following code: 但是到目前为止,我只能使用以下代码选择并打开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)

Do you know what it is missing? 你知道它缺少了什么吗?

You cannot open word files with Excel Application. 您不能使用Excel Application打开Word文件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM