在Excel工作表中插入图像

Kat*_*tya 1 excel vba worksheet-function excel-vba

在我的Office 2010 xlsm工作表中,我创建了一个名为固定大小的Image ActiveX控件Image1.在我看来,以下宏应该将图像路径设置为在单元格中指定的路径B3,但它在"Image1.Picture"行中出现"运行时错误'424':对象必需"错误消息.我检查过imPath等于"C:\some\valid\image\path.jpg".

Private Sub Worksheet_Change(ByVal Target As Range)
   If Target.Address = "$B$3" Then
        imPath = Range("B3")
        Image1.Visible = True         
        Image1.Picture = imPath
        Image1.PictureSizeMode = fmPictureSizeModeZoom   
        Image1.BorderStyle = fmBorderStyleNone    
        Image1.BackStyle = fmBackStyleTransparent
    End If
End Sub
Run Code Online (Sandbox Code Playgroud)

这有什么不对?BTW,有没有办法检查指定的文件是否确实存在?

Joo*_*ook 5

快速查看excel-help,搜索图片,建议您使用以下行:

Image1.Picture = LoadPicture(imPath)
Run Code Online (Sandbox Code Playgroud)

要检查文件是否存在,请使用FileSystemObject

Dim fs as variant
Set fs = CreateObject("Scripting.FileSystemObject")
fs.FileExists(imPath)
Run Code Online (Sandbox Code Playgroud)

编辑

你可以使用的方式

imPath = Target.value
Run Code Online (Sandbox Code Playgroud)

设置imPath(未测试,但非常确定)

  • +1击败我.如果你想避免使用FileSystem对象,你也可以这样做:`如果Dir(imPath)<>""那么`如果Dir返回一个空字符串,那么该路径无效. (3认同)