[英]Excel VBA “On Error” trapping some but not all errors
I have a number of embedded charts in a workbook.我在工作簿中有许多嵌入式图表。 Some of the charts have a rectangle called "rectangle 1" and I want to modify those rectangles.
一些图表有一个名为“矩形 1”的矩形,我想修改这些矩形。 The following code is supposed to do that.
下面的代码应该做到这一点。 It works ok for some charts (both those with and without a rectangle) but then falls over on the "Set rect" line with "run time error -2147024809 (80070057) The item with the specified name wasn't found".
它适用于某些图表(有和没有矩形的图表),但随后在“设置矩形”行上出现“运行时错误 -2147024809 (80070057) 未找到具有指定名称的项目”。
Any idea why the error handler isn't picking this up?知道为什么错误处理程序没有收到这个吗?
Sub RepositionExtrapolationRectangles()
Dim cht As ChartObject
Dim sht As Worksheet
Dim rect As Shape
Dim axs As Axis
For Each sht In ThisWorkbook.Sheets
For Each cht In sht.ChartObjects
With cht.Chart
On Error GoTo skip
Set rect = .Shapes("Rectangle 1")
On Error GoTo 0
Set axs = .Axes(xlCategory)
rect.Left = .PlotArea.InsideLeft + ([CurrentDate] - axs.MinimumScale) / (axs.MaximumScale - axs.MinimumScale) * .PlotArea.InsideWidth
rect.Width = .PlotArea.InsideLeft + .PlotArea.InsideWidth - rect.Left
rect.Top = .PlotArea.InsideTop
rect.Height = .PlotArea.InsideHeight
End With
skip:
Err.Clear
Next
Next
End Sub
I have done some quick testing, and I can't confirm why the following works, but it does:我已经进行了一些快速测试,但我无法确认以下工作的原因,但确实如此:
Use On Error GoTo -1
instead of Err.Clear
, to clear your Error Handling Object.使用
On Error GoTo -1
而不是Err.Clear
来清除错误处理 Object。
It seems that just using Err.Clear
is not resetting it properly, so it cannot trap the error the second time it occurs.似乎仅使用
Err.Clear
并没有正确重置它,因此它无法在第二次发生错误时捕获错误。
At first, I thought that this might be because of the For Each
loop, but rewriting the test code without a loop did not work, nor did rewriting it to not use with
either.起初,我认为这可能是因为
For Each
循环,但是在没有循环的情况下重写测试代码不起作用,也没有将其重写为不with
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.