首页 > 解决方案 > 初始化时从工作表向用户窗体添加图片

问题描述

我正在尝试编写一个脚本,允许我将工作簿中包含的图片动态加载到我的工作簿userform中,以使工作簿完全可移植。我想出了以下似乎可行的方法,但是有一条线我不明白为什么没有它就行不通。如果我删除该行.ChartArea.Select,图像将不会加载。但是,如果我把它留在里面它工作正常。理想情况下,我想删除它,这样我就可以避免使用无意义的Select. 谁能解释一下?

Option Explicit

Private Sub UserForm_Initialize()
    Me.Picture = LoadPicture(Filename:=ExportMyPicture(Sheet1.Pictures(1)))
    Me.PictureSizeMode = fmPictureSizeModeZoom
End Sub


Private Function ExportMyPicture(pic As Picture) As String
    Dim fName As String

    fName = Environ("Temp") & "/" & pic.Name & ".bmp"

    With pic.Parent.ChartObjects.Add(50, 40, pic.ShapeRange.Width, pic.ShapeRange.Height)
        .Border.LineStyle = 0

        pic.Copy

        With .Chart
            ' Removing the following line stops the picture from loading
            .ChartArea.Select
            .Paste
            If .Export(Filename:=fName, filtername:="bmp") Then
                ExportMyPicture = fName
            End If
        End With
        .Delete
    End With
End Function

演示:

演示

使用此 png: 在此处输入图像描述 url: SO 将其转换为 jpg http://pngimg.com/uploads/cat/cat_PNG50497.png


图片来自 Mikku

在此处输入图像描述

标签: excelvba

解决方案


它看起来像是一个时间问题,这可能是 OLE 对象如何实现其.Copy方法的错误;这个.Select电话给了它回到正轨所需的动力。

有评论说明我们为什么要做这些事情。这是其中一种情况,其中评论只是最好的做法......您的评论一点也不差 - 它解释了为什么,而不是什么- 这正是我们想要评论说的。

' Removing the following line stops the picture from loading
.ChartArea.Select

一些替代方案:

.ChartArea.Select ' Picture.Copy timing issue; this prevents subsequent .Paste from being no-op.
.ChartArea.Select ' HERE BE DRAGONS! Remove this instruction and you'll break the .Paste!

推荐阅读