适用于 Windows 和 MacOS 的 VBA 代码问题,用于文件目录选择

问题描述 投票:0回答:1

VBA 代码可以在 Windows 中运行,但会抛出 运行时错误“91”:未设置对象变量或 With 块变量

调试将此命令显示为问题:

If .Show = -1 Then

Dim strPath As String
Dim strFile As String
Dim fd As Office.FileDialog
strPath = ""
While (strPath = "")
    'Open the File Dialog Box for the User to Select a Folder to Save to
    Set fd = Application.FileDialog(msoFileDialogFolderPicker)
    Dim vrtSelectedItem As Variant
    'Validate that the Selection is a Valid Directory
    With fd
        If .Show = -1 Then
         For Each vrtSelectedItem In .SelectedItems
             'Grab the Folder Path Data
             strPath = vrtSelectedItem
             'Turn off Events and Alerts so we can save in the background
             Application.DisplayAlerts = False
             Application.EnableEvents = False
             'Must Keep the , 52 (.xlsx) or 51(.xlsm) at End for the Correct File Format
             ActiveWorkbook.SaveAS strPath & "\" & Cells(63, 4), 51
             'Turn on Alerts After Saving
             'Application.EnableEvents = True
             Application.DisplayAlerts = True
             'Delete the Macro button in the New Form
             'ActiveSheet.Shapes("Button 6").Delete
             ActiveWorkbook.Save
         Next vrtSelectedItem
        Else
            'Inform the User that they MUST select a Folder to Continue
            strPath = ""
            MsgBox "Please select a folder"
        End If
    End With
Wend
excel vba savefiledialog
1个回答
0
投票

错误

也许

fd
就是
Nothing
。文档解释了这些可能的罪魁祸首:

您正在尝试引用已设置为 Nothing 的对象。

您正在尝试访问未正确声明的数组变量的元素。

您需要调试您的应用程序,找出

fd
结果是什么,并确保它已正确初始化。还要验证您的
Show
对象是否存在
fd
以及它是否是您所期望的,即属性或字段而不是过程等。

调试您的应用程序并查看

fd
是否转换为对象或到底发生了什么。它可能是
Nothing
或与您期望的类型不同。

© www.soinside.com 2019 - 2024. All rights reserved.