Word VBA综合练习:数组+函数+查找+图片插入+转形状+简单定位
一、代码
- Sub 查找文字插入印章(doc As Document, findText As String, Optional MatchWildCards = True)
- Dim arr() As Range '存入查找到的“盖章”的位置
- Dim i As Long: i = 0
- Dim j As Long
- Dim fw As Range
- 'Dim 继续查 As Boolean
-
- Set fw = ThisDocument.Range
-
- With fw.Find
- .ClearFormatting
- .Forward = True
- .MatchWildCards = MatchWildCards
- .Text = findText
- .Wrap = wdFindStop
- Do While .Execute
- i = i + 1
- ReDim Preserve arr(1 To i)
- j = Int((fw.Start + fw.End) / 2)
- Set arr(i) = doc.Range(j, j)
- Loop
- End With
-
- Dim isp As InlineShape
- Dim sp As Shape
- For i = UBound(arr) To LBound(arr) Step -1
- arr(i).Select
- Set isp = doc.InlineShapes.AddPicture(doc.Path & "\印章.png", False, True, arr(i))
- isp.ConvertToShape
- Set sp = doc.Shapes(doc.Shapes.Count)
- With sp
- .WrapFormat.Type = wdWrapFront
- .Top = .Top - .Height / 2
- .Left = .Left - .Width / 2
- End With
- Next i
-
- Erase arr
- Set doc = Nothing
- Set fw = Nothing
- Set isp = Nothing
- Set sp = Nothing
- End Sub
- Sub 主程序()
- Dim t0 As Single: t0 = Timer
- Application.ScreenUpdating = False
-
- 查找文字插入印章 ActiveDocument, "盖章"
-
- Application.ScreenUpdating = True
- MsgBox "完成 " & "用时" & Timer - t0 & "秒!"
- End Sub
复制代码 二、图示
三、更多Office VBA问题
欢迎查看我的主页多个专栏:守候 - 知乎 (zhihu.com)
https://www.zhihu.com/people/shou-hou-ysys/columns
|