在特定页面上插入图像(Microsoft Word)
Suman需要使用宏在特定文档的第10页上插入图像。他想知道在宏中执行此操作的最佳方法。
如果要使图像成为第10页上的唯一内容,那么任务就很简单:使用宏定位第10页,插入图像,然后在图像后插入分页符。然后,这会将图像之后的所有内容都向上翻一页,以使旧页面10变为页面11,页面11变为页面12,依此类推。
Sub InsertImage1() Dim PicPath As String PicPath = "C:\My Pictures\My Scans\scan0002.jpg" ActiveDocument.GoTo(What:=wdGoToPage, Count:=10).Select Selection.InlineShapes.AddPicture FileName:=PicPath, _ LinkToFile:=False, SaveWithDocument:=True Selection.InsertBreak Type:=wdPageBreak End Sub
宏将图像插入为嵌入式形状。如果愿意,可以将图像插入为浮动形状,这样可以使文本环绕在图像上。以下宏可以做到这一点,以及将图像居中在页面中心:
Sub InsertImage2() Dim PicPath As String Dim aShape As Shape PicPath = "C:\My Pictures\My Scans\scan0002.jpg" ActiveDocument.GoTo(What:=wdGoToPage, Count:=10).Select Set aShape = Selection.InlineShapes.AddPicture(FileName:=PicPath, _ LinkToFile:=False, SaveWithDocument:=True).ConvertToShape With aShape .WrapFormat.Type = wdWrapTight .RelativeHorizontalPosition = wdRelativeHorizontalPositionPage .RelativeVerticalPosition = wdRelativeVerticalPositionPage .Top = wdShapeCenter .Left = wdShapeCenter .Select End With End Sub
如果您想用图像替换现有图像(也许用更新的图像),则可以使用更复杂的宏来替换。
下面的宏将在所需页面上定位第一张图像,并将其替换为嵌入式形状。
Sub ReplaceImage() Dim r1 As Range Dim r2 As Range Dim nPages As Long Dim nP As Long Dim PicPath As String Dim sTemp As String PicPath = "C:\My Pictures\My Scans\scan0002.jpg" nP = 10 ' Page number on which to replace the image sTemp = "" nPages = ActiveDocument.ComputeStatistics(statistic:=wdStatisticPages) If nP > nPages Then sTemp = "You are trying to go to a non-existent page" Else Set r1 = ActiveDocument.GoTo(What:=wdGoToPage, Count:=nP) If nP = nPages Then Set r2 = ActiveDocument.Range r1.End = r2.End Else Set r2 = ActiveDocument.GoTo(What:=wdGoToPage, Count:=nP + 1) r1.End = r2.Start - 2 End If If r1.InlineShapes.Count = 0 Then sTemp = "Page " & nP & " does not have an inline picture" Else r1.InlineShapes(1).Select Selection.InlineShapes.AddPicture FileName:=PicPath, _ LinkToFile:=False, SaveWithDocument:=True End If End If If sTemp > "" Then MsgBox sTemp End Sub
_WordTips_是您进行经济有效的Microsoft Word培训的来源。
(Microsoft Word是世界上最流行的文字处理软件。)本技巧(13139)适用于Microsoft Word 2007、2010、2013、2016、2019和Office 365中的Word。