使用查找:方法'对象的'范围'_Worksheet'失败“

时间:2013-07-03 11:16:20

标签: excel excel-vba vba

我想写一个宏,在所有工作表中锁定某些单元格 - 从A12到R的最后一行。事实是,我得到了

  

错误1004:“对象'方法'范围'_Worksheet'失败”

在行

LastRow = wSheet.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row)

有人可以帮帮我吗?谢谢!

Option Explicit

Sub ProtectAll()

Dim wSheet          As Worksheet
Dim Pwd             As String
Dim LastRow         As Integer

Pwd = InputBox("Enter your password to protect all worksheets", "Password Input")
For Each wSheet In Worksheets
LastRow = wSheet.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    wSheet.Range(Cells(12, 1), Cells(LastRow, 18)).Select
    wSheet.Protect Password:=Pwd, AllowFiltering:=True
Next wSheet

End Sub

1 个答案:

答案 0 :(得分:3)

如果工作表为空,则代码将失败,因为它当前假设在设置LastRow时至少找到一个非空单元格。

尝试使用范围对象,在使用Not Nothing之前测试它是LastRow

更新:为了完整性添加了一项检查以查看工作表是否已受到保护,如果是,则跳过并注意这些

Option Explicit

Sub ProtectAll()

Dim wSheet          As Worksheet
Dim Pwd             As String
Dim rng1 As Range
Dim strProt As String

Pwd = InputBox("Enter your password to protect all worksheets", "Password Input")
For Each wSheet In Worksheets
Set rng1 = wSheet.Cells.Find(What:="*", After:=wSheet.[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rng1 Is Nothing Then
With wSheet
If .ProtectContents Then
strProt = strProt & .Name & vbNewLine
Else
    .Range(.Cells(12, 1), .Cells(rng1.Row, 18)).Locked = True
    .Protect Password:=Pwd, AllowFiltering:=True
End If
End With
End If
Next wSheet

If Len(strProt) > 0 Then MsgBox strProt, , "These sheet were already protected so were skipped"

End Sub