此代码允许我插入图像。我用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
答案 0 :(得分:1)
尝试此代码
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