Excel 2016 vba Insert and resize picture to range

前端 未结 1 360
别那么骄傲
别那么骄傲 2021-01-16 06:42

2 weeks ago I created a code to insert pictures, position them to a range and resize them to that range. The code worked flawlessly and I generated a 100 page report with it

相关标签:
1条回答
  • 2021-01-16 07:30

    The issue is that your pictures are rotated 90deg. When accessing the position and size properties, adjustment needs to be made for the rotation, like this

    To determine if the image is rotated, examine the .ShapeRange.Rotation property

    With FotoOverview
        .ShapeRange.LockAspectRatio = msoFalse
        If .ShapeRange.Rotation = 90! Or .ShapeRange.Rotation = 270! Then
            .Height = RangeOverview.Width
            .Width = RangeOverview.Height
            .Top = RangeOverview.Top - (.Height - .Width) / 2#
            .Left = RangeOverview.Left + (.Height - .Width) / 2#
        Else
            .Width = RangeOverview.Width
            .Height = RangeOverview.Height
            .Top = RangeOverview.Top
            .Left = RangeOverview.Left
        End If
    End With
    

    Explanation of why this works

    If you have a picture with its Rotation property != 0, the Top, Left, Height, Width property values are for the un-rotated image.

    Example if an image looks like this, and its Rotation property = 90 (or 270)

    Then its Top, Left, Height, Width property values are actually based on this

    So to position it over a Range, you need to calculate Picture size and position based on the range position but adjusted for the rotation, as shown in the code

    0 讨论(0)
提交回复
热议问题