2013-07-03 64 views
2

我想寫一個宏,在所有工作表中鎖定某些單元格 - 從A12到R的最後一行。是的,我得到使用查找:方法'範圍'的對象'_Worksheet'失敗「

錯誤1004:?在行

LastRow = wSheet.Cells.Find(What:="*", After:=[A1], SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row) 「方法 '範圍' 對象中」_Worksheet失敗「

誰能幫我謝謝!因爲它目前假定它找到至少一個非空單元時它設置LastRow

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 
+0

這個心不是你如何保護細胞。請看[這個答案](http://stackoverflow.com/questions/16684297/hiding-formulas-in-formula-bar/16686868#16686868) – 2013-07-03 11:28:23

+1

刪除'After:= [A1],'part或qualify the [ A1]與wsheet – JosieP

回答

3

您的代碼將失敗,如果片材是空白的。

嘗試使用範圍對象代替,在使用LastRow之前測試它是Not Nothing

更新:對於完整性添加了一個檢查,看看錶已經受保護的,如果是這樣跳過和OTES這些

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 
+0

仍然不起作用(甚至在刪除註釋'wSheet.Range(單元格(12,1),單元格(rng1.Row,18))之後)選擇') – atomoutside

+0

相同的行和相同的錯誤(1004)。當我運行你的代碼時,它鎖定工作表,但不鎖定單元格。 – atomoutside

+0

@我知道這在鎖定細胞方面確實如此。但它沒有解釋運行時錯誤。 – brettdj

相關問題