簡體   English   中英

VBA打開Excel或/和Word文件

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

我正在嘗試在用戶表單中設置命令按鈕,以允許用戶一次打開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)

你知道它缺少了什么嗎?

您不能使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM