我找到了一个解决办法!
以前在Excel2003中用picture.insert方法写的代码,到了Excel2010中只能插入链接,图片不能随文件一起保存,不得不改为shapes.addpicture, 也同样遇到上面所说的图片宽高比例的问题。经过一悉研究,好像找到了完美的方法,请各位指正。
-----------------------------------------
Shapes.AddPicture 最后两个参数用-1,-1表示按图片原始尺寸插入
ActiveSheet.Shapes(ActiveSheet.Shapes.Count)可以引用刚插入的图片,从而可以读取图片宽和高,以及进行缩放。
例:
假如图片所在路径为 PicPath,要插入单元格为A1,即Cells(1,1),若要插入的图片自动适应A1单元格,并且保持宽高比,可用以下代码:
With Cells(1, 1)
PicL = .Left + .Width * 0.05
PicT = .Top + .Height * 0.05
PicW = .Width * 0.9
PicH = .Height * 0.9
End With
With ActiveSheet.Shapes.AddPicture(PicPath, True, True, 0, 0, -1, -1)
End With
Set shp = ActiveSheet.Shapes(ActiveSheet.Shapes.Count)
rh = PicH / shp.Height
rw = PicW / shp.Width
r = IIf(rw > rh, rh, rw)
shp.Left = PicL
shp.Top = PicT
shp.ScaleWidth r, msoFalse, msoScaleFromTopLeft
--------------------------------------
如果配上循环语句,可以批量插入图片。