Why do you sometimes need to select an object to avoid "The object does not support this property or method"

I noticed that sometimes I get an error:

Runtime Error '438':

The object does not support this property or method.

in Excel VBA, but if I call .selectfor the object first, this error will disappear.

For example, recently I wanted to resize some related images on a worksheet, and I recorded the following using a macro recorder:

ActiveSheet.Shapes.Range(Array("Picture 3")).Select
Selection.ShapeRange.Height = 303.12

This code obviously works great. Then I changed the code as follows:

Dim sheetReport as Worksheet
Set sheetReport = Worksheets("Report")

With sheetReport
    Dim pictureNumber As Long
    For pictureNumber 1 to 3
        .Shapes.Range("Picture " & pictureNumber).ShapeRange.Height = 303.12
    Next pictureNumber
End With

And now I get the error mentioned above, however, if then I change this code to

Dim sheetReport as Worksheet
Set sheetReport = Worksheets("Report")

With sheetReport
    Dim pictureNumber As Long
    For pictureNumber 1 to 3
        .Shapes.Range("Picture " & pictureNumber).Select
        Selection.ShapeRange.Height = 303.12
    Next pictureNumber
End With

He is working again. But, of course, I will not need to select each picture to change its property Height?

+4
1

.

 Sub PictureResizing()

      Dim sheetReport As Worksheet
      Set sheetReport = ThisWorkbook.Worksheets("Report")

      Dim pictureNumber As Long

      With sheetReport

           For pictureNumber = 1 To 3

           .Shapes("Picture " & pictureNumber).Height = 303.12

           Next pictureNumber

      End With

 End Sub
+4

All Articles