简体   繁体   English

Excel VBA:如果工作表受到保护,则无法使用特殊单元格

[英]Excel VBA: use of specialcells doesn't work if worksheet is protected

I have a piece of Excel VBA code that works OK if the worksheet is unprotected but does not when protected.如果工作表不受保护但不受保护,我有一段 Excel VBA 代码可以正常工作。 I have read the previous similar queries but do not think they apply in this case - the suggested fixes were not applicable or required repeated unprotecting/reprotecting the worksheet which I would like to avoid if possible.我已经阅读了以前的类似查询,但认为它们不适用于这种情况 - 建议的修复不适用或需要重复取消保护/重新保护工作表,如果可能的话,我希望避免。

My code looks like this:我的代码如下所示:

Dim NonEmptyCells As Range
Dim Cell As Range

On Error Goto Fin
Set NonEmptyCells = Range("D3:H6").SpecialCells(xlCellTypeBlanks)

For Each Cell In NonEmptyCells 

    '   do stuff with cell

Next Cell

Fin:
On Error GoTo 0

The use of 'On Error' is to avoid the loop when there are zero empty cells found. 'On Error' 的使用是为了在找到零个空单元格时避免循环。

The Range(D3:H6) has cell formatting set so the cells are not locked and not hidden. Range(D3:H6)设置了单元格格式,因此单元格不会被锁定和隐藏。

When the worksheet is not protected the specialcells line correctly returns the range of blank cells, however when protected special cells always errors as if no empty cells are found.当工作表不受保护时,特殊单元格行会正确返回空白单元格的范围,但是当受保护的特殊单元格总是错误时,就好像找不到空单元格一样。

All help appreciated.所有帮助表示赞赏。

You could use Userinterfaceonly when protection is set.设置保护时,您可以仅使用 Userinterface。 Macro's will work, sheet will be protected against changes done by user him/her self.宏将起作用,工作表将受到保护,防止用户自己进行更改。

In the ThisWorkbook-module-section:在 ThisWorkbook-module-section 中:

Private Sub Workbook_Open()
Worksheets("Sheet1").Protect Password:="yourPassword", UserInterFaceOnly:=True
End Sub

adjust your password and sheetname, (make sure the workbook-open is event has run when running your macro ie reopening it)调整您的密码和工作表名称,(确保在运行宏时已运行 workbook-open is 事件,即重新打开它)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM