打开文件对话框获取Excel

我已经写了一些需要Excel文件并更新Word文件中的标签(ActiveX控件)的Word VBA。 这个Excel文件唯一的将会改变每个月的path和文件名。 如何添加“打开文件”对话框,而不是每月编辑2个variables,以便用户select要使用的Excel文件?

这是我现在拥有的:

Sub Update() Dim objExcel As New Excel.Application Dim exWb As Excel.Workbook PathWork = "C:\My Documents\2015-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 

这里是一个简化的macros,它将允许用户只selectMacro-Enabled Excels。 我不能评论以前的答案,因为我没有赢得足够的声誉评论答案。 请介意一下。

 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 

你可以尝试这样的事情

PathWorkreplacePathWorkDialogbox

 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