打开文件对话框得到 Excel

Open File dialog box to get Excel

我写了一些 Word VBA,它使用 Excel 文件并更新 Word 文件中的标签(ActiveX 控件)。唯一的问题是这个 Excel 文件每个月都会更改路径和文件名。我不是每个月编辑 2 个变量,而是如何添加“打开文件”对话框以便用户选择要使用的 Excel 文件?

这是我现在拥有的:

Sub Update()
    Dim objExcel As New Excel.Application
    Dim exWb As Excel.Workbook

    PathWork = "C:\My Documents15-05 Report\"
    CalcFile = "May2015-data.xlsx"

    Set exWb=objExcel.Workbooks.Open(FileName:=PathWork & CalcFile)
    ThisDocument.date.Caption=exWb.Sheets("Data").Cells(1,1)
End Sub

你可以试试这样的

PathWorkCalcFile替换为Dialogbox

With Dialogs(wdDialogFileOpen)
    If .Display Then
        If .Name <> "" Then
            Set exWb = Workbooks.Open(.Name)
            sPath = exWb.Path
        End If
    Else
        MsgBox "No file selected"
    End If
End With

完成 CODE 应该是这样的

Option Explicit

Sub Update()
    Dim objExcel As New Excel.Application
    Dim exWb As Excel.Workbook
    Dim sPath As String

    '// Dialog box here to select excel file
    With Dialogs(wdDialogFileOpen)
        If .Display Then
            If .Name <> "" Then
                Set exWb = Workbooks.Open(.Name)
                sPath = exWb.Path
            End If
            Set exWb = objExcel.Workbooks.Open(FileName:=sPath)
            ActiveDocument.Date.Caption = exWb.Sheets("Data").Cells(1, 1)
        Else
            MsgBox "No file selected"
        End If
    End With
    Set objExcel = Nothing
    Set exWb = Nothing
End Sub

这是一个简化的宏,它将允许用户 select 仅启用宏的 Excel。我无法对之前的答案发表评论,因为我没有获得足够的声誉来对答案发表评论。请注意。

Public Sub GetCaptionFromExcel()
    Dim objExcel As New Excel.Application, exWb As Workbook
    With Application.FileDialog(msoFileDialogFilePicker)
        .Title = "Select Macro-Enabled Excel Files"
        .Filters.Add "Macro-Enabled Excel Files", "*.xlsm", 1
        If .Show <> -1 Then Exit Sub

        Set exWb = objExcel.Workbooks.Open(.SelectedItems(1))
        '*** Use the values from excel here***
        MsgBox exWb.Sheets("Data").Cells(1, 1)
        '*** Close the opened Excel file
        exWb.Close
    End With
End Sub