在活动单元格中选择一张图片

时间:2014-01-14 00:15:10

标签: excel vba excel-vba

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

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"

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

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."

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

如果选择了单元格,则无法调整图片。您需要选择图片本身。根据SO上的this question,图片集合没有记录。当我用谷歌搜索它时,我也找不到它。我相信一旦你选择了单元格,你就可以从the ShapeRange collection获得图片对象。它有一个必需的参数 index ,但是如果你只有一个形状,那个值应该是1.希望这会指向正确的方向。