简体   繁体   中英

Image resize excel macro

I have a macro where I am resizing an image. What should happen: an image is located inside the cell and when I click it once it enlarges, and when I click it again it goes back to normal. But when I click the image to return it to normal it does not it, goes out of the cell. The code is below and an image to see what happens when I have clicked an image

Sub Picture1_Click()
Dim shp As Shape
    Dim big As Single, small As Single
    Dim shpDouH As Double, shpDouOriH As Double
    big = 3
    small = 1

    On Error Resume Next
    Set shp = ActiveSheet.Shapes(Application.Caller)
    With shp
        shpDouH = .Height
        .ScaleHeight 1, msoTrue, msoScaleFromTopLeft
        shpDouOriH = .Height
     
        If Round(shpDouH / shpDouOriH, 2) = big Then
            .ScaleHeight small, msoTrue, msoScaleFromTopLeft
            .ScaleWidth small, msoTrue, msoScaleFromTopLeft
            .ZOrder msoSendToBack
        Else
            .ScaleHeight big, msoTrue, msoScaleFromTopLeft
            .ScaleWidth big, msoTrue, msoScaleFromTopLeft
            .ZOrder msoBringToFront
        End If
    End With

End Sub

在此处输入图像描述

How can I reset the image to what it was previously?

The problem in your code is the use of ScaleHeight. This method resizes the image in relation to its current size, so .ScaleHeight 1, msoTrue, msoScaleFromTopLeft does nothing; it basically resizes the image to the size it already has.

Read more about ScaleHeight here: Shape.ScaleHeight method (Excel)

As your code is written, shpDouH will always be equal to shpDouOriH , which means that Round(shpDouH / shpDouOriH, 2) will always calculate to exactly 1. That defeats your If... Then... Else logic. Each time you click, the image size will increase by a scale factor of 3; it will never shrink.

The easiest way to shrink the image back to its original dimensions is if you are able to define the maximum dimensions for an un-enlarged image. Then you can use a test along the lines of If shp.Height > MaxHeight Then . In basic concept, if the current height is less than MaxHeight, then scale by a factor of 3; else scale by a factor of 1/3. This should work if the original images are all roughly the same size.

Otherwise you will need to pick a method to record the original dimensions before each image is enlarged.

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