我有一个很大的 Word docx 文件,里面有很多文本和图片。我想一次性将边框/框架样式应用于所有图片。我不想对所有图片单独执行此操作。
所以我相信宏是可行的方法,但我不太擅长创建 Word 宏。我认为这是个开始,但在尝试将设置应用于元素时出现错误<hr>
。
这是我使用的宏代码。我怀疑只需进行一点小调整就可以修复它(允许代码针对所有图片对象运行)。
Sub addborder()
'
' addborder Macro
'
'
Dim i As Long, j As Long
With ActiveDocument.Range
For i = 1 To .InlineShapes.Count
With .InlineShapes(i)
For j = 1 To .Borders.Count
.Borders(j).LineStyle = wdLineStyleSingle
.Borders(j).Color = wdColorAutomatic
Next j
End With
Next i
End With
End Sub
谢谢。
添加:
请注意,文档<hr>
中有一些内容,并且该元素正在停止宏(无法将这些参数应用于<hr>
元素)。因此,宏必须仅选择图片。
答案1
Word 文档中的所有图片都必须格式化为“与文本对齐”,这段代码才能正常工作。如果以任何其他方式让文档文本环绕图像,则会导致VBA 形状对象而不是 InlineShape 对象。
此外,边境s对象包括所有 4 条边。您不需要第二个 For...Next 语句循环 4 次来设置每条边的样式和颜色。
最后一点是,当我将其设置为默认宽度大小时,边框线在我的图片上不容易看到。您也可以设置 Linewidth 属性,看看它是否有效。
在 Office 2007 中,这对我来说有效:
Dim i As Long, j As Long
With ActiveDocument.Range
For i = 1 To .InlineShapes.Count
With .InlineShapes(i)
.Borders(1).LineStyle = wdLineStyleSingle
.Borders(1).Color = wdColorAutomatic
' optional .Borders(1).LineWidth = wdLineWidth225pt
End With
Next i
End With
编辑:
关于您的<hr>
错误。并非所有 InlineShape 对象都是图片。您可以在 VBA 代码中指定仅选择类型为图片的 InlineShape。
这可能就是为什么我更喜欢直接将对象引用为“InlineShape”,而不是将它们全部与“InlineShape-s”组合在一起。您无法使用 InlineShape-s 轻松获取“Type”属性。
Dim inshape As InlineShape
Dim ashape As shape
For Each inshape In ActiveDocument.InlineShapes
If inshape.Type = wdInlineShapePicture Then
inshape.Borders(1).LineStyle = wdLineStyleSingle
inshape.Borders(1).Color = wdColorAutomatic
'optional inshape.Borders(1).LineWidth = wdLineWidth225pt
End If
Next
'The second loop will look for pictures formatted as Shape objects
For Each ashape In ActiveDocument.Shapes
If ashape.Type = msoPicture Then
ashape.Line.Style = msoLineSingle
ashape.Line.Weight = 0.5 'default size is 0.5 pts'
End If
Next
答案2
我真的很喜欢 Cathy 对这个问题的回答,但我只想补充一点,你不一定非要使用Borders
的成员InlineShape
来获取周围的线条,你可以像Line
使用普通 一样使用 成员Shape
,如下所示:
Option Explicit
Sub PicturesAll_Borders_Show()
'for pictures which are "In Line with Text"
Dim inShp As InlineShape
For Each inShp In ActiveDocument.InlineShapes
If inShp.Type = wdInlineShapePicture Then
With inShp.Line
.Visible = True
.Style = msoLineSingle
.Weight = 1
.ForeColor.RGB = RGB(0, 0, 0)
End With
End If
Next inShp
'for pictures which are "With Text Wrapping"
Dim shp As Shape
For Each shp In ActiveDocument.Shapes
If shp.Type = msoPicture Then
With shp.Line
.Visible = True
.Style = msoLineSingle
.Weight = 1
.ForeColor.RGB = RGB(0, 0, 0)
End With
End If
Next shp
End Sub
我还发明了一种快捷方法来隐藏所有图片的边框,以防有人稍后发现需要它。
Sub PicturesAll_Borders_Hide()
'for pictures which are "In Line with Text"
Dim inShp As InlineShape
For Each inShp In ActiveDocument.InlineShapes
If inShp.Type = wdInlineShapePicture Then inShp.Line.Visible = False
Next inShp
'for pictures which are "With Text Wrapping"
Dim shp As Shape
For Each shp In ActiveDocument.Shapes
If shp.Type = msoPicture Then shp.Line.Visible = False
Next shp
End Sub