excel - 初始化时从工作表向用户窗体添加图片
问题描述
我正在尝试编写一个脚本,允许我将工作簿中包含的图片动态加载到我的工作簿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
解决方案
它看起来像是一个时间问题,这可能是 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!
推荐阅读
- r - is.data.frame(x) 中的错误:不能强制“list”对象键入“double”
- php - PHP 注意:类 mysqli_result 的对象无法转换为 int
- vue.js - 如何从 NuxtJS 中的 fetch 或 asyncData 挂钩访问 vuex 存储?
- c++ - 棒球卡(数组和结构)
- c++ - C++ 初学者:循环问题
- swift - 使用组合获取枚举发布者
- python-3.x - 我如何获得一张表格并将其放入 Excel 中而无需长代码
- javascript - 如何将多个值保存到 sessionStorage 并显示它们?
- java - java.lang.IllegalStateException:未设置位置,错误
- regex - 使用正则表达式提取特定的 URL 部分并重写