使用FileDialog从Word打开Excel

我想要做的是:

  • 按下我的Microsoft Word文档中的一个button,它会提示我在文件浏览器中select一个文档。
  • select我的文档我的Word文档中的相关字段将被填充。
  • 这将根据文档(月份)中的信息填充,并使用Match函数search所选Excel文档中的正确行/列并返回值。

我困在我的代码下面的FileDialog(msoFileDialogFilePicker)部分。

为了我的文档的目的,我不能进入直接文件path,文件path需要从FileDialog函数(或类似的东西)中获取。

我也尝试过GetOpenFilename 。 我不确定如何做到这一点。 我的代码目前打开FileDialog,让我select一个文件,但我不能将文件path传递到我的colNum1线。

我得到的错误是运行时错误'91'。 对象variables或With Blockvariables未设置。

我很乐意提供build议和任何帮助,非常感谢。

 Sub KPI_Button() ' ' KPI_Button Macro Dim objExcel As New Excel.Application Dim exWb As Excel.Workbook Dim strFile As String Dim Doc As String Dim Res As Integer Dim dlgSaveAs As FileDialog Doc = ThisDocument.Name Set dlgSaveAs = Application.FileDialog(msoFileDialogFilePicker) Res = dlgSaveAs.Show colNum1 = WorksheetFunction.Match("(Month)", ActiveWorkbook.Sheets("Sheet1").Range("A2:I2"), 0) ThisDocument.hoursworkedMonth.Caption = exWb.Sheets("Sheet1").Cells(3, colNum1) exWb.Close Set exWb = Nothing End Sub 

尝试一个对话框,指定一个Excel扩展名为:

 Sub GetNames() With Application.FileDialog(msoFileDialogFilePicker) .AllowMultiSelect = False .Filters.Clear .Filters.Add "Excel files", "*.xls*", 1 If .Show = True Then If .SelectedItems.Count > 0 Then 'this is the path you need MsgBox .SelectedItems(1) Else MsgBox "no valid selection" End If End If End With End Sub