You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA代码在Windows正常运行,MacOS下触发Run-Time Error '91'求助

MacOS下VBA FileDialog报错Run-Time Error '91'的解决方案

问题根源

Mac版Office对Office.FileDialog的支持存在兼容性缺陷,Set fd = Application.FileDialog(msoFileDialogFolderPicker)语句在Mac环境中无法成功初始化对象实例,导致后续With fd块操作触发Run-Time Error '91'。此外原代码硬编码的Windows路径分隔符\,在Mac平台也会导致保存路径无效。

修复方案

替换文件夹选择逻辑为Mac原生AppleScript调用,同时处理跨平台路径兼容问题:

Dim strPath As String
Dim strFileName As String
strPath = ""
strFileName = Cells(63, 4).Value ' 提前提取文件名,减少循环内重复读取操作

While strPath = ""
    #If Mac Then
        ' Mac平台调用AppleScript实现文件夹选择
        Dim scriptStr As String
        scriptStr = "return POSIX path of (choose folder with prompt ""请选择保存文件夹"" as string)"
        On Error Resume Next ' 捕获用户取消选择的异常
        strPath = MacScript(scriptStr)
        On Error GoTo 0
        
        If strPath = "" Then
            MsgBox "请选择一个文件夹以继续"
        End If
    #Else
        ' Windows平台保留原有FileDialog逻辑
        Dim fd As Office.FileDialog
        Dim vrtSelectedItem As Variant
        Set fd = Application.FileDialog(msoFileDialogFolderPicker)
        
        With fd
            If .Show = -1 Then
                For Each vrtSelectedItem In .SelectedItems
                    strPath = vrtSelectedItem
                Next vrtSelectedItem
            Else
                strPath = ""
                MsgBox "Please select a folder"
            End If
        End With
    #End If
    
    ' 仅当获取到有效路径时执行保存操作
    If strPath <> "" Then
        Application.DisplayAlerts = False
        Application.EnableEvents = False
        
        ' 使用系统原生路径分隔符,自动适配Windows/Mac
        Dim fullPath As String
        fullPath = strPath & Application.PathSeparator & strFileName
        
        ' 保存为启用宏的工作簿格式(51对应xlOpenXMLWorkbookMacroEnabled)
        ActiveWorkbook.SaveAs fullPath, 51
        
        Application.DisplayAlerts = True
        Application.EnableEvents = True
        ActiveWorkbook.Save
    End If
Wend

关键修改说明

  1. 跨平台条件编译:通过#If Mac Then分支实现平台差异化逻辑,避免兼容性冲突
  2. Mac原生选择逻辑:用MacScript调用AppleScript获取文件夹路径,确保Mac环境下正常运行
  3. 路径分隔符兼容:使用Application.PathSeparator替代硬编码的\,自动适配不同系统的路径格式
  4. 错误处理优化:在Mac分支中添加异常捕获,处理用户取消选择的场景
  5. 代码结构优化:将文件名提取、保存逻辑移出循环,减少冗余操作

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 00:50:05