在活动单元格中选择一张图片 [英] Select a picture in the active cell

查看:34
本文介绍了在活动单元格中选择一张图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在活动单元格内选择图片?我正在尝试制作一个宏,用于插入图片并将其大小调整为单元格的大小.在一些帮助下,我制作了以下代码来插入图片:

How do I select a picture inside an active cell? I am trying to make a macro that inserts a picture and resizes it to the size of the cell. With some help, I have made the following code to insert the picture:

ActiveCell.Select
Dim picname As String
picname = ActiveCell.Value
ActiveCell.Offset(-1, 0).Select
ActiveSheet.Pictures.Insert "C:\Users\Briet\Documents\PAJ\pic-presentation\Images\" & picname & ".jpg"

插入图片后,将选择其容器单元格,而不是实际图片.因此,以下将图片调整为单元格大小的代码不起作用:

Once the picture is inserted, its container cell is selected, but not the actual picture. So the following code, which resizes the picture to the cell, does not work:

On Error GoTo NOT_SHAPE
Dim PicWtoHRatio As Single
Dim CellWtoHRatio As Single
With Selection
PicWtoHRatio = .Width / .Height
End With
With Selection.TopLeftCell
CellWtoHRatio = .Width / .RowHeight
End With
Select Case PicWtoHRatio / CellWtoHRatio
Case Is > 1
With Selection
.Width = .TopLeftCell.Width
.Height = .Width / PicWtoHRatio
End With
Case Else
With Selection
.Height = .TopLeftCell.RowHeight
.Width = .Height * PicWtoHRatio
End With
End Select
With Selection
.Top = .TopLeftCell.Top
.Left = .TopLeftCell.Left
End With
Exit Sub
NOT_SHAPE:
MsgBox "Select a picture before running this macro."

推荐答案

Insert()返回对插入图片的引用,因此您可以直接使用它.

Insert() returns a reference to the inserted picture, so you can work directly with that.

Sub Tester()

Dim shp, rng As Range

    Set rng = ActiveSheet.Range("C3")

    Set shp = ActiveSheet.Pictures.Insert("C:\_Stuff\pic.jpg")
    With shp
        .Top = rng.Top
        .Left = rng.Left
        .ShapeRange.LockAspectRatio = msoTrue
        .Width = .Width / Application.Max(.Width / rng.Width, _
                                          .Height / rng.Height)
    End With

End Sub

这篇关于在活动单元格中选择一张图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆