首页 > 解决方案 > 如果找不到图像,则显示默认图像

问题描述

此代码允许我插入图像。我在 TXT_CODE 中写入并在文件 IMAGES 中查找它。

我想要的是使用默认图像,以防图像不在文件中。

例如,图像应该说:图像不可用。

Set Img = ActiveSheet.Pictures.Insert(ThisWorkbook.Path & "\Images\" & Txt_Code.Value & ".png")
With Img
    'Resize Picture to fit in the range....
    .Left = ActiveSheet.Range("C" & Fila).Left
    .Top = ActiveSheet.Range("C" & Fila).Top
    .ShapeRange.LockAspectRatio = msoFalse
    .Width = ActiveSheet.Range("C" & Fila).Width
    .Height = ActiveSheet.Range("C" & Fila).Height
    .Placement = 1
    .PrintObject = True
End With

我想用一个 IF 条件来做,比如......

If Txt_Code.Value is not found in file Images then
    show default_Image.png
else
    the code above
end if

标签: excelvba

解决方案


试试这个代码

Private Sub CommandButton1_Click()
    Dim r As Range, Img As Object, sFilePath As String, sFileDefault As String, sFile As String, Fila As Long
    sFilePath = ThisWorkbook.Path & "\Images\" & Txt_Code.Value & ".png"
    Fila = 5
    Set r = ActiveSheet.Range("C" & Fila)
    If Dir(sFilePath) <> "" Then
        sFile = sFilePath
    Else
        MsgBox "Image Not Found", vbExclamation
        sFileDefault = ThisWorkbook.Path & "\Images\DefaultImage.png"
        If Dir(sFileDefault) = "" Then
            MsgBox "No Default Image. Process Cancelled.", vbExclamation: Exit Sub
        Else
            sFile = sFileDefault
        End If
    End If
    Set Img = ActiveSheet.Pictures.Insert(sFile)
    With Img
        .Left = r.Left
        .Top = r.Top
        .ShapeRange.LockAspectRatio = msoFalse
        .Width = r.Width
        .Height = r.Height
        .Placement = 1
        .PrintObject = True
    End With
End Sub

推荐阅读