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

使用VBA保存PDF时遇到Error 1004应用程序定义错误

解决VBA导出PDF时的Error 1004问题

错误原因分析

  • 文件名参数写法错误:你在ExportAsFixedFormat的filename参数里把strPath & strFileName用双引号包裹,导致VBA将其识别为固定字符串而非实际路径+文件名,系统找不到对应路径触发1004错误。
  • 代码结构逻辑错误:导出PDF的语句写在了FileDialog的With块内部,但End With却放在导出语句之后,不符合逻辑执行顺序。
  • 可选优化点:频繁使用Select/Activate会降低代码稳定性,直接引用工作表对象更可靠。

修正后的代码

Sub Gem_beregner_ny()
    Dim wsUdskrift As Worksheet
    Dim wsOplysninger As Worksheet
    Dim strFileName As String
    Dim strPath As String
    
    ' 直接绑定工作表对象,避免依赖Select
    Set wsUdskrift = ThisWorkbook.Sheets("Udskrift")
    Set wsOplysninger = ThisWorkbook.Sheets("Oplysningesskema")
    
    wsUdskrift.Visible = True
    strFileName = wsUdskrift.Range("F1").Value
    
    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        If .Show = True Then
            strPath = .SelectedItems(1) & "\"
        Else
            ' 用户取消选择时执行的操作
            wsUdskrift.Visible = False
            wsOplysninger.Activate
            wsOplysninger.Range("D8").Select
            wsOplysninger.Protect "Salg-2022!"
            ThisWorkbook.Protect "Salg-2022!"
            Exit Sub
        End If
    End With ' 先结束文件选择对话框的作用域
    
    ' 正确导出PDF,拼接实际路径和文件名
    wsUdskrift.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:=strPath & strFileName, _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
    
    ' 后续界面调整
    wsUdskrift.Visible = False
    wsOplysninger.Activate
End Sub

关键修正说明

  1. 移除了冗余的Select操作,通过绑定工作表对象直接操作,避免因当前激活表变化导致的意外错误。
  2. 修复了Filename参数的拼接方式,去掉包裹变量的双引号,让VBA识别为动态路径。
  3. 调整了With块的结束位置,确保文件选择完成后再执行导出操作,符合逻辑顺序。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:31:22