excel - 初始化时从工作表向用户窗体添加图片

标签 excel vba

我正在尝试编写一个脚本,允许我将工作簿中包含的图片加载到我的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

演示:

Demo

使用这个png:
enter image description here
url:所以将其转换为 jpg
http://pngimg.com/uploads/cat/cat_PNG50497.png

图片来自 Mikku

enter image description here

最佳答案

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

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

' 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!

关于excel - 初始化时从工作表向用户窗体添加图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57207090/

相关文章:

R - 自动调整 Excel 列宽

database - 如何从数据库中获取 Excel 文件 (BLOB) 并对其进行读/写操作?

vba - 附加到文本文件 VBA

vba - 将数据透视表添加到具有同一工作表上的数据的新工作表

vb.net - VB 和 VBA 的优缺点?

arrays - VBA:从空数组元素输出 "blank"而不是零

excel - 找不到 OleDB 数据提供程序 VBA/Excel

excel - 输入新行并复制上面单元格中的公式

java - Apache POI 保留现有的 Excel 格式样式

Excel VBA 如何使用超链接在工作表之间将信息从一个单元格复制到另一个单元格