【问题标题】:Using Find: Method 'Range' Of Object '_Worksheet' failed"使用查找:对象“_Worksheet”的方法“范围”失败”
【发布时间】:2013-07-03 11:16:19
【问题描述】:

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

错误 1004:“对象 '_Worksheet' 的方法 'Range' 失败”

排队

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

【问题讨论】:

  • 这不是你保护细胞的方式。请看this answer
  • 删除 After:=[A1], 部分或使用 wsheet 限定 [A1]

标签: excel vba


【解决方案1】:

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

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

更新:为了完整起见,添加了检查工作表是否已受到保护,如果是,则跳过并记下这些

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

【讨论】:

  • 仍然不起作用(即使在删除取消注释 wSheet.Range(Cells(12, 1), Cells(rng1.Row, 18)).Select 之后)
  • 同一行和同一错误 (1004)。当我运行您的代码时,它会锁定工作表,但不会锁定单元格。
  • @mehow 在锁定单元格时确实如此。但它并不能解释运行时错误。
  • + 1 做得很好。如果您使用的是.FIND,那么最好添加错误处理。我已经讨论过了HERE
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多