[英]VBA Excel - Application-Defined or Object-Defined Error
我正在努力弄清楚为什么在运行此代码时出现上述错误。 有时有效,有时无效? 代码位于工作表而不是模块中,我怀疑这可能是问题所在,但是同一段代码在工作簿的另一工作表中运行良好。
请有人能告诉我我在想什么吗?
谢谢。
Sub DeleteRow()
On Error GoTo error_handler
Dim Button As Shape
Dim CellinRowtoDelete As Range
'Run sub routine
ClearSearchandFilter
Application.ScreenUpdating = False
'Determine which row needs to be deleted
ButtonLocation = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Address
Range(ButtonLocation).Select
'Select and delete buttons before deleting the row
Set CellinRowtoDelete = ActiveCell
For Each Button In ActiveSheet.Shapes
If Not Application.Intersect(Range(Button.TopLeftCell.Address), CellinRowtoDelete) Is Nothing Then
Button.Select
Button.Delete
End If
Next
'Delete the row
ActiveCell.EntireRow.Delete
'Re-format cells in row 8 with a red box incase the bottom has been removed by deleting row 9
Range("W8:AM8").Select
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Color = -16776961
.TintAndShade = 0
.Weight = xlMedium
End With
Range("X5").Select
Application.ScreenUpdating = True
Exit Sub
Error_handler:
MsgBox Err.Description
End Sub
首先,您实际上不应真正使用.Select
, .Activate
或任何Active
。 它会弄乱你的代码超过了它所能帮助它(除了极少数情况下)。
其次,不要检查与单元格的交点,而应尝试对整行进行检查。 由于无论如何您都将删除该行中的所有按钮(如果我正确理解的话),这将更加准确,因为即使离中心的位置也会被删除。 这听起来可能令人困惑,但请忍受我。
请尝试以下代码。
Sub DeleteRow()
Dim Button As Shape
Dim RowToDelete As Range
'Run sub routine
ClearSearchandFilter
Application.ScreenUpdating = False
'Determine which row needs to be deleted
ButtonLocation = ActiveSheet.Shapes(Application.Caller).TopLeftCell.Address
Set RowToDelete = Range(ButtonLocation).EntireRow
'Select and delete buttons before deleting the row
For Each Button In ActiveSheet.Shapes
If Not Application.Intersect(Range(Button.TopLeftCell.Address), RowToDelete) Is Nothing Then
Button.Delete
End If
Next
'Delete the row
RowToDelete.Delete
'Re-format cells in row 8 with a red box incase the bottom has been removed by deleting row 9
With Range("W8:AM8").Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Color = -16776961
.TintAndShade = 0
.Weight = xlMedium
End With
Application.ScreenUpdating = True
End Sub
让我们知道结果如何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.