替换excel工作表中图片怎么保持图片位置和大小不变?
2023-01-26 餐饮美食网 【 字体:大 中 小 】
Q:我原先在工作表中放置了一个图片,现在我想使用新的图片来替换该图片,但是要保持图片的位置和大小不变,如何使用VBA代码实现?
A:在VBE中插入一个标准模块,输入如下代码:
SubChangePicLoc()
On Error GoTo ErrHandle
Dim blnFlag As Boolean
Dim shp As Shape
Dim dblTop As Double
Dim dblLeft As Double
Dim dblHeight As Double
Dim dblWidth As Double
Dim FileToOpen As Variant
‘检查所选取的是形状还是单元格
blnFlag = False
For Each shp In ActiveSheet.Shapes
If shp.Name = Selection.Name Then
blnFlag = True
Exit For
Else
blnFlag = False
End If
Next shp
ErrHandle:
On Error GoTo endHandle
If blnFlag = True Then
With Selection.ShapeRange
‘保存所选图片的属性
dblTop = .Top
dblLeft = .Left
dblHeight = .Height
dblWidth = .Width
End With
‘删除所选图片
Selection.Copy
Selection.Delete
‘插入新图片
FileToOpen =Application.GetOpenFilename
If FileToOpen <> False Then
ActiveSheet.Pictures.Insert(FileToOpen).Select
Else
MsgBox “没有选择图片文件!”
ActiveSheet.Paste
End If
‘将原图片属性应用于新图片
With Selection.ShapeRange
.Top = dblTop
.Left = dblLeft
.Height = dblHeight
.Width = dblWidth
End With
Else
MsgBox “请选择图片,不要选择单元格区域.”
End If
endHandle:
End Sub
首先选取工作表中要替换的图片,然后运行代码,效果如下所示。
如何自制蛋挞
肉火烧面怎么和面
奶茶几分糖好喝
过桥米线是哪里的?
面霜和乳液的区别
怎么摘隐形眼镜
粉饼和散粉的区别
冷烫和热烫的区别
高品质香水如何鉴别?用三步就可以解决
如何去除黑眼圈