I am having a bit of trouble with errors occurring in a loop in VBA. First, here is the code I am using
dl = 20
For dnme = 1 To 3
Select Case dnme
Case 1
drnme = kt + " 90"
nme = "door90"
drnme1 = nme
Case 2
drnme = kt + " dec"
nme = "door70" 'decorative glazed'
Case 3
drnme = kt + " gl"
nme = "door80" 'plain glazed'
End Select
On Error GoTo ErrorHandler
Set sh = Worksheets("kitchen doors").Shapes(drnme) 'This line here is where the problem is'
sh.Copy
ActiveSheet.Paste
Selection.ShapeRange.Name = nme
Selection.ShapeRange.Top = 50
Selection.ShapeRange.Left = dl
Selection.ShapeRange.Width = 150
Selection.ShapeRange.Height = 220
25
dl = dl + 160
Next dnme
Exit Sub
ErrorHandler:
GoTo 25
The problem is that when it tries to access the shape, the shape doesn’t always exist. The first time through the loop, this is fine. It goes to the ErrorHandler and everything works good. The second time it goes through and can’t find the shape, it comes up with the “End/Debug” error box. I can’t work out why it doesn’t just go straight to the ErrorHandler. Any suggestions?
First of all you have a for loop with only 3 iterations, and you have a switch case for three!!. why can’t you move your common code to a new function and call it thrice?
And more over each error has a unique number (incase of VBA errors like Subscript out of range etc, or a description if its a generic number like 1004, and other office errors). You need to check the error number, then decide how to proceed, if to skip the part or work around.
Please go through this code..I have moved your comon code to a new function, and in that function we will be resizing the shape.
If the shape is missing then we will just return false, and move to next shape.