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

Word VBA用户窗体取消/保护文档时带Range的If Then逻辑运行异常

问题原因分析
  • 事件递归触发:这是核心问题。在ComboBox6_Change事件的末尾,你判断值为No时直接修改了窗体控件ComboBox6的Text属性,这个操作会再次触发ComboBox6的Change事件。第二次进入事件时,第一次执行的代码还没走到ActiveDocument.Protect步骤,文档处于未保护状态,此时执行ActiveDocument.Unprotect就会抛出「文档已经处于未保护状态」的错误。
  • 缺少保护状态判断:你所有的解保护操作都没有提前判断文档当前的保护状态,只要重复执行解保护代码就会报错。
  • 冗余代码:代码中For iiia = 1 To 1的循环没有任何实际作用,属于无效代码。
    另外补充:你在正常运行的ComboBox5_Change过程中,用控件名ComboBox5作为Range变量名,会覆盖同名控件的引用,属于不规范写法,后续也可能引发逻辑异常,建议修改为和ComboBox6一致的命名规则,比如rngComboBox5。
解决步骤

1. 操作前先判断文档保护状态

所有执行Unprotect的位置,先判断当前文档是否处于保护状态,避免重复解保护报错。恢复保护时也增加状态判断,避免重复执行保护操作抛出异常。

2. 修改控件值前禁用事件,避免递归触发

修改窗体控件属性前先关闭事件触发,修改完成后再恢复,防止事件递归嵌套执行。

3. 优化冗余代码

删除无效的单次循环逻辑,简化代码结构。

修正后的完整代码
Private Sub ComboBox6_Change()
    ' 先判断文档保护状态再执行解保护
    If ActiveDocument.ProtectionType <> wdNoProtection Then
        ActiveDocument.Unprotect "password"
    End If
    ' 临时禁用事件,避免修改控件值触发递归
    Application.EnableEvents = False

    Dim rngComboBox6 As Range
    Dim sssaText As String

    Set rngComboBox6 = ActiveDocument.Bookmarks("bmfcs").Range
    sssaText = Me.ComboBox6.Value

    If Me.ComboBox6.Value = "Yes" Then
        sssaText = sssaText & Chr(13) & "200" _
          & Chr(13) & "200.1" _
          & Chr(13) & "" _
          & Chr(13) & "OEBS" _
          & Chr(13) & "" _
          & Chr(13) & "21c" _
          & Chr(13) & "" _
          & Chr(13) & "22c" _
          & Chr(13) & "Yes" _
          & Chr(13) & "" _
          & Chr(13) & "Yes" _
          & Chr(13) & "Two" _
          & Chr(13) & "" _
          & Chr(13) & "ES2a.1" _
          & Chr(13) & "" _
          & Chr(13) & "222" _
          & Chr(13) & "" _
          & Chr(13) & "222a" _
          & Chr(13) & "222b" _
          & Chr(13) & "" _
          & Chr(13) & "3.a.1" _
          & Chr(13) & "" _
          & Chr(13) & "NA" _
          & Chr(13) & "" _
          & Chr(13) & "I. TuuVa" _
          & Chr(13) & "717217" _
          & Chr(13) & "" _
          & Chr(13) & "1212" _
          & Chr(13) & "" _
          & Chr(13) & "D.1" _
          & Chr(13) & "F2B-4"
    End If
            
    rngComboBox6.Text = sssaText
    ActiveDocument.Bookmarks.Add "bmfcs", rngComboBox6
    
    If Me.ComboBox6.Value = "No" Then
        Me.ComboBox6.Text = ""
    End If
    
    ' 先判断状态再恢复保护
    If ActiveDocument.ProtectionType = wdNoProtection Then
        ActiveDocument.Protect wdAllowOnlyFormFields, NoReset:=True, Password:="password"
    End If
    ' 恢复事件触发能力
    Application.EnableEvents = True
End Sub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 07:27:04