我有一个Excel 2007工作表,其中包含许多用作菜单选项的按钮和标签(即用户单击按钮,带有图像的标签),并显示表单或其他内容。
通过指定Control的 Picture 属性并使用完整图像文件路径调用 LoadPicture ()方法,可以在VBA中加载按钮和标签的这些图像/图标作为参数,如So。
With SomeFormObject
.cmdOpenFile.Picture = LoadPicture("F:\projectname\images\fileopen.BMP")
End With
这种为按钮加载图像的方法,其他控件导致了2个问题。
1)它为每个用户创建了对图像文件和物理位置的依赖关系,因此如果用户没有映射驱动器并且文件存在,则VBA会因文件运行时错误或找不到路径而失败。
2)
如果图像在共享驱动器上(这种情况),应用程序会变得很慢
我希望消除这两个问题,并以某种方式将图标,图像加载到内部控制中,而不会对外部图像文件产生任何外部依赖。
在Excel 2007 VBA中实现此目的的最佳方法是什么?
我无法提交任何Visual Basic 6.0 / Visual Studio样式的“资源文件编辑器”/功能来完成此任务。
请指教!谢谢
-Shiva @ mycodetrip.com
答案 0 :(得分:3)
我真的希望有一种更简单的方法可以做到这一点,但这是我发现的唯一一种方法:
理念是:
您可以将图片嵌入工作表中,每次要为Command设置图片时,都可以将它们从工作表导出到文件并通过LoadPicture
加载。通过VBA导出嵌入式图片的唯一方法是首先将其设为Chart
。
以下代码基于 johnske
中的'Export pictures from Excel'Option Explicit
Sub setAllPictures()
setPicture "Picture 18", "CommandButtonOpen"
setPicture "Picture 3", "CommandButtonClose"
End Sub
Sub setPicture(pictureName As String, commandName As String)
Dim pictureSheet As Worksheet
Dim targetSheet As Worksheet
Dim embeddedPicture As Picture
Dim pictureChart As Chart
Dim MyPicture As String
Dim PicWidth As Long
Dim PicHeight As Long
Set pictureSheet = Sheets("NameOfYourPictureSheet") ' <- to Change '
Set targetSheet = Sheets("NameOfYourSheet") ' <- to Change '
Set embeddedPicture = pictureSheet.Shapes(pictureName).OLEFormat.Object
With embeddedPicture
MyPicture = .Name
PicHeight = .ShapeRange.Height
PicWidth = .ShapeRange.Width
End With
Charts.Add
ActiveChart.Location Where:=xlLocationAsObject, Name:=pictureSheet.Name
Set pictureChart = ActiveChart
embeddedPicture.Border.LineStyle = 0
With pictureChart.Parent
.Width = PicWidth
.Height = PicHeight
End With
With pictureSheet
.Select
.Shapes(MyPicture).Copy
With pictureChart
.ChartArea.Select
.Paste
End With
.ChartObjects(1).Chart.Export Filename:="temp.jpg", FilterName:="jpg"
End With
pictureChart.Parent.Delete
Application.ScreenUpdating = True
targetSheet.Shapes(commandName).OLEFormat.Object.Object.Picture = LoadPicture("temp.jpg")
Set pictureChart = Nothing
Set embeddedPicture = Nothing
Set targetSheet = Nothing
Set pictureSheet = Nothing
End Sub
Sub listPictures()
' Helper Function to get the Names of the Picture-Shapes '
Dim pictureSheet As Worksheet
Dim sheetShape As Shape
Set pictureSheet = Sheets("NameOfYourSheet")
For Each sheetShape In pictureSheet.Shapes
If Left(sheetShape.Name, 7) = "Picture" Then Debug.Print sheetShape.Name
Next sheetShape
Set sheetShape = Nothing
Set pictureSheet = Nothing
End Sub
结束: 从映射的网络驱动器加载图像似乎不那么混乱,并且不应该有那么大的速度差异。
答案 1 :(得分:0)
我能想到的2个替代方案:form.img.picture=pastepicture
和= oleobjects("ActiveXPictureName").object.picture
。