I am trying to set it up so that if a user checks a check box, it makes a sheet visible and inserts an image, scaled to fit within a certain area. It works just fine for any image that is landscape oriented where the height is 75% of the width (or less). But when I insert a portrait image I am having issues. At first it was making it too tall, so I adjusted the code to account for the height (and then center the image in the viewport), but now the portrait images lose their aspect ratio and look distorted. I have ShapeRange.LockAspectRatio = msoTrue, so it shouldn't be able to alter the aspect ratio, right?
Here is the code I have so far.
Private Sub cbIMG1_Click()
Dim strFileName As String
Dim WD As Single
Dim objPic As Picture
Dim IMG1 As Shape
Dim rngDest As Range
Dim SHT As Worksheet
On Error Resume Next
ThisWorkbook.Sheets("Image1").Visible = cbIMG1.Value
If cbIMG1.Value = True Then
Set SHT = ThisWorkbook.Sheets("Image1")
Set IMG1 = SHT.Shapes("IMG1")
IMG1.Delete
strFileName = Application.GetOpenFilename( _
FileFilter:="Images (*.jpg;*.gif;*.png),*.jpg;*.gif;*.png", _
Title:="Please select an image...")
If strFileName = "False" Then Exit Sub
objPic.ShapeRange.LockAspectRatio = msoTrue
Set rngDest = SHT.Range("B5:L27")
Set objPic = SHT.Pictures.Insert(strFileName)
With objPic
.ShapeRange.LockAspectRatio = msoTrue
.Left = rngDest.Left
.Top = rngDest.Top
.Width = rngDest.Width
.Name = "IMG1"
If .Height > 345 Then
WD = 345 / .Height
.Height = 345
.Width = objPic.Width * WD
.Left = objPic.Left + ((rngDest.Width - objPic.Width) / 2)
'SHT.Range("F30").Value = WD *Returns a value for me to confirm the aspect ratio while I run tests
End If
If .Height < 345 Then
.Top = objPic.Top + ((rngDest.Height - objPic.Height) / 2)
End If
End With
End If
End Sub
What am I missing here? Thanks!!
Bookmarks