使用 Word 的打开文件对话框

Using Word's Open File Dialog

我想使用我的 VSTO 加载项中的内置“打开文件”对话框。显示对话框时我必须设置 InitialFileName 。不幸的是,这个 属性 在对话框中不存在 class:

var Dlg = Word.Dialogs.Item(WdWordDialog.wdDialogFileOpen);
Dlg.InitialFileName = SomePath; //COMPILE ERROR: no such property

尝试将其转换为 FileDialog 也不起作用:

var Dlg = Word.Dialogs.Item(WdWordDialog.wdDialogFileOpen) as FileDialog;
Dlg.InitialFileName = SomePath; //RUNTIME EXCEPTION: null reference

我在这里错过了什么?

注意:我使用的是 Add-in Express。

您的 post 中的 Microsoft 页面显示 属性 用于 msoFileDialogFilePicker 对话框,但您的代码使用的是 wdDialogFileOpen。 MS 页面上的示例代码工作正常,但尝试将 属性 用于 wdDialogFileOpen 也会生成 运行 时间错误。

所以这有效:

Sub ThisWorks()

    Dim fd As FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

    Dim vrtSelectedItem As Variant

    With fd
        .InitialFileName = "C:\folder\printer_ink_test.docx"

        'If the user presses the action button...
        If .Show = -1 Then

            For Each vrtSelectedItem In .SelectedItems
                MsgBox "Selected item's path: " & vrtSelectedItem
            Next vrtSelectedItem
        'If the user presses Cancel...
        Else
        End If
    End With

    Set fd = Nothing

End Sub

但这失败了:

Sub ThisFails()

    Dim fd As Dialog

    Set fd = Application.Dialogs(wdDialogFileOpen)

    Dim vrtSelectedItem As Variant

    With fd
        ' This line causes a run-time error
        .InitialFileName = "C:\folder\printer_ink_test.docx"

        'If the user presses the action button...
        If .Show = -1 Then
            For Each vrtSelectedItem In .SelectedItems
                MsgBox "Selected item's path: " & vrtSelectedItem
            Next vrtSelectedItem
        'If the user presses Cancel...
        Else
        End If
    End With

    Set fd = Nothing

End Sub

知道了。我必须将我的应用程序对象转换为 Microsoft.Office.Interop.Word.Application 才能访问 FileDialog 成员。以下代码有效:

var Dlg = ((Microsoft.Office.Interop.Word.Application)Word).get_FileDialog(MsoFileDialogType.msoFileDialogFilePicker);
Dlg.InitialFileName = STRfolderroot + STRfoldertemplatescommon + "\" + TheModality + "\" + TheModality + " " + TheStudyType + "\";
Dlg.Show();

抱歉截图,我正在使用我的 phone 来回答。

根据 google 书中的图片,这就是 Excel 的做法:Globals.ThisWorkbook.ThisApplication.FileDialog

根据此 link,对于 MS Word,它是这样完成的:

Office.FileDialog dialog = app.get_FileDialog(
  Office.MsoFileDialogType.msoFileDialogFilePicker);
//dialog.InitialFileName  <-- set initial file name
dialog.Show();