我的代码是清除4个不同工作表上不同范围的未受保护单元格的内容。它很慢,并且给了我一个“'联盟方法'Clobal失败”。有什么建议?我的代码附在下面
Sub ClearAllUnLocked()
Application.ScreenUpdating = False
Dim r As Range, rKlear As Range
Set rclear = Nothing
For Each r In ThisWorkbook.Worksheets("A").Range("F7:AA832")
If r.Locked = False Then
If rKlear Is Nothing Then
Set rKlear = r
Else
Set rKlear = Union(rKlear, r)
End If
End If
Next r
rKlear.ClearContents
For Each r In ThisWorkbook.Worksheets("B").Range("D7:Y806")
If r.Locked = False Then
If rKlear Is Nothing Then
Set rKlear = r
Else
Set rKlear = Union(rKlear, r)
End If
End If
Next r
rKlear.ClearContents
For Each r In ThisWorkbook.Worksheets("E").Range("F7:AA855")
If r.Locked = False Then
If rKlear Is Nothing Then
Set rKlear = r
Else
Set rKlear = Union(rKlear, r)
End If
End If
Next r
rKlear.ClearContents
For Each r In ThisWorkbook.Worksheets("X").Range("F7:AA3006")
If r.Locked = False Then
If rKlear Is Nothing Then
Set rKlear = r
Else
Set rKlear = Union(rKlear, r)
End If
End If
Next r
rKlear.ClearContents
Application.ScreenUpdating = True
End Sub
由于
答案 0 :(得分:2)
不是答案,但您的代码会因重复过多而受到影响。这将更容易调试,并做同样的事情:
Sub ClearAllUnLocked()
Application.ScreenUpdating = False
ClearUnlocked ThisWorkbook.Worksheets("A").Range("F7:AA832")
ClearUnlocked ThisWorkbook.Worksheets("B").Range("D7:Y806")
ClearUnlocked ThisWorkbook.Worksheets("E").Range("F7:AA855")
ClearUnlocked ThisWorkbook.Worksheets("X").Range("F7:AA3006")
Application.ScreenUpdating = True
End Sub
Sub ClearUnlocked(rng As Range)
Dim rngClear As Range, c As Range
For Each c In rng.Cells
If Not c.Locked Then
If rngClear Is Nothing Then
Set rngClear = c
Else
Set rngClear = Union(rngClear, r)
End If
End If
Next c
rngClear.ClearContents
End Sub
虽然这些范围很大,但性能不会很好。
答案 1 :(得分:2)
ozgrid有一个巧妙的(hacky)解决方案:
Sub EmptyUnlocked()
ActiveSheet.Protect
On Error Resume Next
ActiveSheet.Range("A1:F14") = ""
On Error GoTo 0
ActiveSheet.Unprotect
End Sub
它会尝试清除范围内的所有内容,但会忽略锁定单元格的错误。
就个人而言,由于您似乎在范围内拥有知识/控制(?),因此我将为每个包含 未锁定单元格的工作表定义范围名称。对于每个工作表,使用Ctrl-拖动选择所有相关区域;单击名称框(左上角)并给出一个名称(不带空格)。然后,
Range("the_name").ClearContents
(对于每张纸)。