【发布时间】:2020-05-18 22:24:29
【问题描述】:
我编写了一个小模块来保护我工作簿的所有工作表并保护某些工作表中的某些范围。
代码第一次运行顺利,但尝试第二次运行时出现运行时 1004 错误“应用程序定义或对象定义错误”
我想我可能在以下页面上找到了一些解释: http://support.microsoft.com/kb/178510 但我就是想不通..
有人可以帮我吗?
我的代码如下。
根据首先保护的工作表,可能是这一行
WS.Protection.AllowEditRanges.Add Title:=titlef _
, Range:=WS.Range("L:R"), Password:="pw2"
或以下引发错误的行
WS.Protection.AllowEditRanges.Add Title:=titlec _
, Range:=WS.Range("N:T"), Password:="pw3"
Sub Protect()
Dim WS As Worksheet
Dim pWord As String
pWord = "pw1"
Dim aer As AllowEditRange
For Each WS In Worksheets
WS.Unprotect pWord
For Each aer In WS.Protection.AllowEditRanges
aer.Delete
Next aer
Next WS
Dim counterf As Integer
Dim counterc As Integer
counterf = 1
counterc = 1
Dim titlef As String
Dim titlec As String
For Each WS In ActiveWorkbook.Worksheets
WS.Protect Password:=pWord, AllowFormattingCells:=True, AllowFormattingColumns:=True, AllowFormattingRows:=True
WS.EnableSelection = xlNoRestrictions
If InStr(UCase(WS.Name), "FORM") Then
titlef = "Volumes form faits par poste" & counterf
WS.Unprotect pWord
WS.Protection.AllowEditRanges.Add Title:=titlef _
, Range:=WS.Range("L:R"), Password:="pw2"
WS.Protect pWord
counterf = counterf + 1
ElseIf InStr(UCase(WS.Name), "COND") Then
titlec = "Volumes cond faits par poste" & counterc
WS.Unprotect pWord
WS.Protection.AllowEditRanges.Add Title:=titlec _
, Range:=WS.Range("N:T"), Password:="pw3"
WS.Protect pWord
counterc = counterc + 1
End If
Next
End Sub
【问题讨论】:
-
在哪一行抛出错误?
-
放置断点,然后让我们知道错误发生在哪里
-
你说得对,我忘了提到引发错误的行!我会在我原来的帖子中编辑它!
-
我意识到这已经晚了两年,所以它可能完全无关紧要,但您可能会遇到问题,因为您在工作表不受保护的情况下添加了“AllowEditRange”。根据我的经验,AER 只能在工作表受到保护时添加,并且只能在工作表不受保护时删除
标签: excel vba runtime-error