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

在受保护工作表中使用MailEnvelope VBA后重新保护失败求助

解决VBA发送邮件后重新保护工作表的1004错误

错误原因

出现Run-time error '1004'的核心原因:当EnvelopeVisible = True时,工作表处于邮件编辑状态,Excel会锁定工作表的保护操作;原代码未明确指定Range所属工作表,易引发上下文混乱;同时Protect (wspword)的括号写法在VBA过程调用中会导致参数传递异常。

修正后的代码

Sub SEND_()
    Dim tws As Worksheet
    Dim wspword As String
    Dim auditdate As String
    Dim audittime As String

    Set tws = ThisWorkbook.Worksheets(8)
    wspword = "Hello123"
    
    ' 从目标工作表读取数据,避免上下文错误
    auditdate = tws.Range("D8").Text
    audittime = tws.Range("D10").Text

    tws.Unprotect wspword
    
    ' 直接操作目标工作表范围,无需Select
    With tws.MailEnvelope
        .Introduction = "use this field to add message"
        .Item.To = ""
        .Item.Subject = "Results | " & audittime & " on " & auditdate
        ' 如需自动发送邮件,添加该行:.Item.Send
    End With
    
    ' 关闭邮件信封可见性,释放工作表锁定
    ThisWorkbook.EnvelopeVisible = False
    
    ' 重新保护工作表,避免括号导致的参数传递问题
    tws.Protect Password:=wspword
End Sub

关键修正点

  • 明确指定工作表范围:所有Range操作添加tws.前缀,避免引用到当前激活的其他工作表
  • 关闭邮件信封:保护工作表前设置EnvelopeVisible = False,解除Excel对工作表的锁定
  • 优化Protect调用:使用命名参数Password:=wspword或直接写tws.Protect wspword,避免括号引发的异常
  • 移除Select操作:VBA中尽量避免Select/Activate,直接操作对象更稳定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 16:22:45