我正在尝试编写一个脚本,允许我将工作簿中包含的图片加载到我的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:所以将其转换为 jpg
http://pngimg.com/uploads/cat/cat_PNG50497.png
图片来自 Mikku
最佳答案
它看起来像是一个时间问题,这可能是 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/