VBA - Application.FileDialog() - 对象不支持此属性或方法错误 438

问题描述

我的代码很简单。

我已经从 VBA 示例站点复制了它:https://docs.microsoft.com/en-us/office/vba/api/office.filedialog

此外,我在网上能找到的所有其他变体都有同样的问题。

我所尝试的只是打开一个文件对话框(类似于文件浏览器),用户可以在其中选择一个或多个文件夹。

但是,我继续收到此错误

enter image description here

然后突出显示这行代码

enter image description here

此外,我还添加了对 Microsoft Office 16.0 对象库的引用,以及我能想到的所有内容

enter image description here

如何解决此问题或使其运行?

谢谢

代码如下:

Sub Main()
 
 'Declare a variable as a FileDialog object.
 Dim fd As FileDialog
 
 'Create a FileDialog object as a File Picker dialog Box.
 Set fd = Application.FileDialog(msoFileDialogFilePicker)
 
 'Declare a variable to contain the path
 'of each selected item. Even though the path is aString,'the variable must be a Variant because For Each...Next
 'routines only work with Variants and Objects.
 Dim vrtSelectedItem As Variant
 
 'Use a With...End With block to reference the FileDialog object.
 With fd
 
 'Use the Show method to display the File Picker dialog Box and return the user's action.
 'The user pressed the button.
 If .Show = -1 Then
 
 'Step through each string in the FileDialogSelectedItems collection.
 For Each vrtSelectedItem In .SelectedItems
 
 'vrtSelectedItem is aString that contains the path of each selected item.
 'You can use any file I/O functions that you want to work with this path.
 'This example displays the path in a message Box.
 MsgBox "The path is: " & vrtSelectedItem
 
 Next vrtSelectedItem
 'The user pressed Cancel.
 Else
 End If
 End With
 
 'Set the object variable to nothing.
 Set fd = nothing
 
End Sub

解决方法

我假设您使用的是 Windows 系统,因为 Application.FileDialog 在 Mac 上不可用/完全支持。

我建议您重新开始,不要添加过多不相关的参考资料。以下工作正常,无需向默认引用添加任何内容:

Sub Demo()
Dim fd As FileDialog,vrtSelectedItem As Variant
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
  If .Show = -1 Then
    For Each vrtSelectedItem In .SelectedItems
      MsgBox "The path is: " & vrtSelectedItem
    Next
  End If
End With
Set fd = Nothing
End Sub

如果代码仍然不适合您,则很可能需要修复/重新安装 Office 或您的 SolidWorks 安装。

有关适用于 Mac 和 PC 的代码,请参阅:https://answers.microsoft.com/en-us/msoffice/forum/msoffice_word-msoffice_custom-mso_365hp/showing-dialogs-word-for-mac-vba/513ea974-378d-4ebe-95c3-a0221a9287ff