使用Word的打开文件对话框

时间:2015-07-04 07:44:26

标签: c# .net vba vsto addin-express

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

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。

3 个答案:

答案 0 :(得分:1)

知道了。我必须将我的应用程序对象强制转换为"containerFields": [ { "label": "First Name", "name": "first_name", "placeholder": "Enter Your first name", "primary": "no", "required": "yes", "type": "text", "input":"text", "enum": "false", "access":"user", "minlength":"10", "maxlength":"150", "rules": [{ "message":"Enter First Name", "minlength":"10", "maxlength":"150", "elementValidate":"aplha" }] }, { "label": "Email", "name": "email", "placeholder": "Enter Your email", "primary": "no", "required": "yes", "type": "text", "input": "email", "access":"user", "rules": [{ "message":"Enter valid email", "elementValidate":"email" }] } ] 才能访问Microsoft.Office.Interop.Word.Application成员。以下代码有效:

FileDialog

答案 1 :(得分:0)

帖子中的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

答案 2 :(得分:0)

很抱歉截图,我正在使用手机接听。

根据Google图书中的图片,您可以按照这种方式进行操作:Globals.ThisWorkbook.ThisApplication.FileDialog

enter image description here

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

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