我需要删除模板中的选定行。Selection.EntireRow.Delete
处理我所有的场景,但只有一个。
当我选择同一行时,在多个选择中Selection.EntireRow.Delete
将抛出 1004 错误。
我写了一个 ErrorHandler 来警告这种情况,然后继续不让模板解锁。
Sub DelRows()
Dim answer As VbMsgBoxResult, LRow As Integer
LRow = Range("D5").Value
If Selection.Cells(1, 1).Row < 9 Or Selection.Cells(1, 1).Row + Selection.Rows.Count > LRow - 1 Then
MsgBox "Forbidden selection."
ElseIf Selection.Rows.Count > LRow - 11 Then
MsgBox "Can't delete all rows."
Else
On Error GoTo ErrHandler
ActiveSheet.Unprotect Password:="xx"
answer = MsgBox("Are you sure you want to delete all rows?", vbOKCancel + vbExclamation, "Warning")
If answer = 1 Then Selection.EntireRow.Delete
Rows((LRow + 2) & ":1048576").EntireRow.Hidden = True
ActiveSheet.Protect Password:="xx", DrawingObjects:=False, Contents:=True, Scenarios:=True, AllowFormattingCells:=True, AllowFormattingRows:=True, AllowFiltering:=True
End If
Exit Sub
ErrHandler:
If Err.Number = 1004 Then
MsgBox "Can't select the same row twice: " & Err.Description
Resume Next
Else
MsgBox Err.Description
Resume Next
End If
End Sub
这件事有效,但我在错误处理方面的经验并不是最好的。我可以用其他方法避免这个错误吗?
我可以检查同一行中的多个选择,还是不值得这样做?
我可能会循环所有选定的单元格,创建一个包含每个区域的行的数组,然后比较结果,但这似乎太过分了。
--最终解决方案--
感谢 Pᴇʜ我设法不仅解决了这个问题,而且同时找到并解决了另外两个问题。
多项选择打破了我的
Selection.Cells(1, 1).Row
和 Selection.Rows.Count
因为他们只关心第一个区域。这两者都可以通过循环区域来修复。 Dim answer As VbMsgBoxResult, LRow As Long, i As Long, RowCount As Long, TopRow As Long
LRow = Range("D5").Value
TopRow = Selection.Cells(1, 1).Row
For i = 1 To Selection.Areas.Count
RowCount = RowCount + Selection.Areas(i).Rows.Count
If Selection.Areas(i).Cells(1, 1).Row < TopRow Then TopRow = Selection.Areas(i).Cells(1, 1).Row
Next i
If TopRow < 9 Or TopRow + RowCount > LRow - 1 Then
MsgBox "Forbidden selection."
ElseIf RowCount > LRow - 11 Then
MsgBox "Can't delete all rows."
Else
ActiveSheet.Unprotect Password:="xx"
answer = MsgBox("Are you sure you want to delete all rows?", vbOKCancel + vbExclamation, "Warning")
If answer = 1 Then Selection.EntireRow.Delete
Rows((LRow + 2) & ":1048576").EntireRow.Hidden = True
ActiveSheet.Protect Password:="xx", DrawingObjects:=False, Contents:=True, Scenarios:=True, AllowFormattingCells:=True, AllowFormattingRows:=True, AllowFiltering:=True
End If
End sub
最佳答案
你可以做一个技巧并使用 Application.Union method
Union(Selection.EntireRow, Selection).delete
这样就避免了一行多选的错误。
根据评论编辑:
Dim i As Long, RowCount As Long
For i = 1 To Selection.Areas.Count
RowCount = RowCount + Selection.Areas(i).Rows.Count
Next i
关于excel - Selection.EntireRow.Delete 错误,可以在行的多列中选择单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53596552/