我有一个宏,可以将图像添加到工作表中
Private Function attachImageMac(ByVal FName As String, ByVal imageName As String)
Dim img
Dim imgWidth, imgHeight As Long
imgWidth = -1
imgHeight = -1
Set img = Sheets("Receipt images").Shapes.AddPicture(fileName:=FName, linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=10, top:=10, width:=imgWidth, height:=imgHeight)
img.Name = imageName
img.LockAspectRatio = msoTrue
Set img = Nothing
End Function
所以,它应该保存带有形状的图像文件,但是之后如何访问该文件? Shape 文档 https://learn.microsoft.com/en-us/office/vba/api/excel.shape 没有提供任何明显的访问方法。
如果您的意思是“如何访问文件”提取插入的图片文件全名,您应该添加一个代码行,使用形状字符串属性来记住相应的全名。否则,Excel不知道与所使用的插入图片文件相关的任何信息:
Private Sub attachImageMac(ByVal FName As String, ByVal imageName As String)
Dim img As Shape
Set img = Sheets("Receipt images").Shapes.AddPicture(fileName:=FName, linktofile:=msoFalse, _
savewithdocument:=msoCTrue, Left:=10, top:=10, width:=-1, height:=-1)
img.Name = imageName
img.LockAspectRatio = msoTrue
img.Title = FName 'this line is necessary to memorize the file full name
Set img = Nothing
End Sub
然后,调用下一个
Function
,使用与上面代码中使用的相同的imageName
:
Function extractPictureOriginalFile(imgName As String) As String
Dim img As Shape
Set img = ActiveSheet.Shapes(imgName)
extractPictureOriginalFile = img.Title
End Function
应该使用下一个测试来调用它
Sub
:
Sub testExtractPictureFile()
Dim imgName As String
imgName = "My Picture" 'use here your previously used/allocated name!
Debug.Print extractPictureOriginalFile(imgName) 'it will return the file full name
'Use Ctrl + G to open Immediate Window
End Sub
它将返回之前插入的图片的全名。
如果您有插入文件全名的列表并且imgName
已从相应的全名中提取,作为不带路径的文件名,您可以通过形状名称与其形状之间的关联来提取相应的信息使用该列表中的完整文件名...