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

我想写一个macros,在所有表中locking某些单元格 – 从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 

如果表单为空白,您的代码将失败,因为它现在假设它在设置LastRow时至lessfind一个非空白单元格。

尝试使用Range对象,在使用LastRow之前testing它是否为Not Nothing

更新:完整性添加检查,看看表是否已经被保护,如果是这样跳过,并ote这些

 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