简体   繁体   中英

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. 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".

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.

It seems that just using Err.Clear is not resetting it properly, so it cannot trap the error the second time it occurs.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM