|
本帖最后由 lzongb 于 2010-11-7 17:04 编辑
谢谢管理员,我的问题已经搞定了。完整代码(借鉴了网络搜索结果)如下:
Private Sub InsertPicture(PictureFileName As String, TargetCell As Range, CenterH As Boolean, CenterV As Boolean)
'在显示区域中插入图片,可以水平居中或垂直居中,还可以缩小以适应显示区域
Dim p As Excel.Picture, _
sh As Excel.Shape, _
t As Double, l As Double, _
w As Double, h As Double, _
wRatio As Double, _
hRatio As Double
With TargetCell
For Each sh In .Parent.Shapes '当连续打印时,删除上一户的图片
If sh.Type = msoLinkedPicture Then sh.Delete
Next
If PictureFileName = "" Then Exit Sub '未指定图片
If Dir(PictureFileName) = "" Then Exit Sub '指定的图片文件不存在
Set p = .Parent.Pictures.Insert(PictureFileName)
t = .Top
l = .Left
w = .Offset(0, 1).Left - .Left
h = .Offset(1, 0).Top - .Top
wRatio = Round(w / p.Width, 2)
hRatio = Round(h / p.Height, 2)
If wRatio < 1 Or hRatio < 1 Then '当图片大于显示区域时进行缩小
p.ShapeRange.LockAspectRatio = msoTrue
If wRatio < hRatio Then
p.ShapeRange.ScaleWidth wRatio, msoTrue, msoScaleFromMiddle
p.ShapeRange.ScaleHeight wRatio, msoTrue, msoScaleFromMiddle
Else
p.ShapeRange.ScaleHeight hRatio, msoTrue, msoScaleFromMiddle
p.ShapeRange.ScaleWidth hRatio, msoTrue, msoScaleFromMiddle
End If
End If
If CenterH Then '水平居中
l = l + w / 2 - p.Width / 2
If l < 1 Then l = 1
End If
If CenterV Then '垂直居中
t = t + h / 2 - p.Height / 2
If t < 1 Then t = 1
End If
End With
' position picture
With p
.Top = t
.Left = l
End With
Set p = Nothing
End Sub
用法示例:InsertPicture "d:\demo.bmp",xlBook.worksheets(1).Range("D1"),true,true |
|