下面的代碼片段更改了單元格的數據驗證狀態,並在Excel-2003工作表不受保護時運行。然而,當我保護工作表中的宏不運行,提高運行時錯誤工作表在MS-Excel中受保護時,如何避免運行時錯誤?
Run-time error '-2147417848 (80010108)':
Method 'Add' of object 'Validation' failed
我已經試過包裝代碼與
Me.unprotect
...
Me.protect
但是,這並不正常工作。那麼,如何在工作表受到保護而沒有上述運行時錯誤的情況下如何修改下面的代碼來工作(即讓代碼修改解鎖單元的驗證)?
更新
我原來的工作簿是Excel 2003,我測試@eJames解決方案在Excel 2007以下定義爲Workbook_Open
Sub WorkBook_Open()
Me.Worksheets("MainTable").Protect contents:=True, userinterfaceonly:=True
End Sub
的代碼仍然失敗,出現以下運行 - 工作表受到保護時出現實時錯誤
Run-time error '1004': Application-defined or object-defined error
Thanks,Azim
代碼段
'cell to add drop down validation list'
dim myNamedRange as String
dim modifyCell as Range
modifyCell = ActiveCell.Offset(0,1)
' set list values based on some conditions not defined for brevitity'
If myCondition then
myNamedRange = "range1"
Else
myNamedRange = "range2"
End If
With modifyCell.Validation
.Delete
'Run time error occurs on the next line'
.Add Type:=xlValidateList, AlertStyle:=xlValidAltertStop, _
Operator:=xlBetween, Formula1:="=" & myNamedRange
...
' skipping more property setting code '
...
End With
可能重複的[如何保護Excel中的單元格,但允許這些被VBA腳本修改](http://stackoverflow.com/questions/125449/how-to-protect-cells-in-excel-but- allow-these-to-be-modified-by-vba-script) – 2014-10-31 09:39:52