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

关闭应用触发Runtime Error 1004:仅ComboBox存值时出现

解决Runtime Error 1004(工作表保护报错)问题

问题根源

  1. UserInterfaceOnly:=True 参数无法在Excel关闭后保留,当文件关闭过程中触发ComboBox1_Change事件时,重新执行Protect操作会因Excel正在释放资源、工作表状态异常导致权限报错。
  2. 仅当ComboBox存有值时,关闭文件的清理操作可能间接触发Change事件;从未激活过ComboBox时该事件不会触发,因此无报错。

修复方案

方案1:避免重复执行保护操作

在执行Protect前检查工作表当前保护状态,防止重复操作引发冲突:

Private Sub ComboBox1_Change()
    ' 检查工作表是否未保护,或保护状态未启用UserInterfaceOnly
    If Not Sheet5.ProtectContents Or Sheet5.ProtectionMode = False Then
        Sheet5.Unprotect Password:="groomingusa"
        Sheet5.Protect Password:="groomingusa", UserInterfaceOnly:=True
    End If
    
    myVarible = ComboBox1.Value
   
    Call PriceAvg
    Call PriceLow
    Call PriceHigh
    Call PriceBlade
    Call PriceShrtComb
    Call PriceMedComb
    Call PriceLngComb
End Sub

方案2:将UserInterfaceOnly设置移至Workbook_Open事件

UserInterfaceOnly状态无法持久化,需在每次打开文件时重新设置:

  1. 打开ThisWorkbook模块,添加以下代码:
Private Sub Workbook_Open()
    Sheet5.Unprotect Password:="groomingusa"
    Sheet5.Protect Password:="groomingusa", UserInterfaceOnly:=True
End Sub
  1. 修改ComboBox1_Change事件,移除重复的保护代码:
Private Sub ComboBox1_Change()
    myVarible = ComboBox1.Value
   
    Call PriceAvg
    Call PriceLow
    Call PriceHigh
    Call PriceBlade
    Call PriceShrtComb
    Call PriceMedComb
    Call PriceLngComb
End Sub

方案3:添加错误捕获忽略关闭时异常

如果不想调整保护逻辑,可通过错误捕获跳过关闭时的报错:

Private Sub ComboBox1_Change()
    On Error Resume Next ' 临时忽略错误,继续执行后续代码
    Sheet5.Protect Password:="groomingusa", UserInterfaceOnly:=True
    On Error GoTo 0 ' 恢复默认错误处理
    
    myVarible = ComboBox1.Value
   
    Call PriceAvg
    Call PriceLow
    Call PriceHigh
    Call PriceBlade
    Call PriceShrtComb
    Call PriceMedComb
    Call PriceLngComb
End Sub

额外提示

  • UserInterfaceOnly:=True仅允许VBA修改受保护工作表,用户操作仍会被限制,但该状态必须每次打开文件时重新设置,Excel不会保存此配置。
  • 可在Workbook_BeforeClose事件中禁用控件,避免关闭时触发Change事件:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
    ComboBox1.Enabled = False
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:55:26