
当一个word文件里有很多张图片时,通过使用vba可以批量将文件中所有图片修改为同样大小,令文件看起来更加整洁有序
假设有一个word文件,中间有多张大小不一的图片,需要将其中的图片按比例缩放为一样高或者一样宽。
在菜单栏中选择“开发工具”选项卡,点击“Visual Basic”打开VBA编辑器。
在打开的编辑器中输入以下代码,稍后做详细解释。
Sub 设为统一宽度()
Dim n '图片个数
Dim picwidth
Dim picheight
Dim newWidth
newWidth = 300
On Error Resume Next '忽略错误
For n = 1 To ActiveDocument.InlineShapes.Count 'InlineShapes 类型图片
picheight = ActiveDocument.InlineShapes(n).Height
picwidth = ActiveDocument.InlineShapes(n).Width
ActiveDocument.InlineShapes(n).Height = picheight * newWidth / picwidth
ActiveDocument.InlineShapes(n).Width = newWidth
Next n
For n = 1 To ActiveDocument.Shapes.Count 'Shapes类型图片
picheight = ActiveDocument.Shapes(n).Height
picwidth = ActiveDocument.Shapes(n).Width
Debug.Print picheight
ActiveDocument.InlineShapes(n).Height = picheight * newWidth / picwidth
ActiveDocument.InlineShapes(n).Width = newWidth
Next n
End Sub
Sub 设为统一高度()
Dim n '图片个数
Dim picwidth
Dim picheight
Dim newHeight
newHeight = 200 '设为统一高度时修改此数值
On Error Resume Next '忽略错误
For n = 1 To ActiveDocument.InlineShapes.Count 'InlineShapes 类型图片
picheight = ActiveDocument.InlineShapes(n).Height
picwidth = ActiveDocument.InlineShapes(n).Width
ActiveDocument.InlineShapes(n).Height = newHeight
ActiveDocument.InlineShapes(n).Width = picwidth * newHeight / picheight
Next n
For n = 1 To ActiveDocument.Shapes.Count 'Shapes类型图片
picheight = ActiveDocument.Shapes(n).Height
picwidth = ActiveDocument.Shapes(n).Width
Debug.Print picheight
ActiveDocument.InlineShapes(n).Height = newHeight
ActiveDocument.InlineShapes(n).Width = picwidth * newHeight / picheight
Next n
End Sub
sub后面就是一个过程的名字,想要运行哪个过程,就把活动光标放在哪个过程体里面,或者在右上角选择相应名称的过程。按F5键,或者单击菜单栏上的运行按钮,运行相应过程。
如果运行的是“设为统一宽度”,将得到以下结果。
如果运行的是“设为统一高度”,将得到以下结果。
也可以通过直接设置代码中的ActiveDocument.InlineShapes(n).Height、ActiveDocument.InlineShapes(n).Width、ActiveDocument.InlineShapes(n).Height、ActiveDocument.InlineShapes(n).Width的数值来修改图片,例如“ActiveDocument.InlineShapes(n).Height=200”。但是这样就不是等比例缩放了。
