我想使用宏在word文档中插入文本。例如,我有一个这样的段落:
This is an example. This is an example. This is an example. This is an example. This is an example. This is an example. This is an example.
我想将其更改为类似的内容(每30个字符插入 @@@ )。
This is an example. This is an_@@@_ example. This is an example. T_@@@_his is an example. This is an _@@@_example. This is an example. T_@@@_his is an example.
正如您所看到的,_@@@_
有时会破坏这个词。所以我也希望将文本插入最近的空格而不是单词的中间。
以下代码有效,但它会将文本插入到单词的中间。
Sub AddPageNumber1000Chr()
Dim doc As Document
Dim CharPerPage As Integer
Set doc = ActiveDocument
CharPerPage = 1000
Dim k As Integer
k = doc.Range.Characters.Count / CharPerPage - 1
For i = doc.Range.Characters.Count To 1 Step -1
If i Mod CharPerPage = 0 Then
doc.Range.Characters(i) = doc.Range.Characters(i) & "@@@" & k & "@@@"
k = k - 1
End If
If i = 1 Then
doc.Range.Characters(i) = "Total Page: " & doc.Range.Characters.Count / CharPerPage & " x " & CharPerPage & vbNewLine & doc.Range.Characters(i)
End If
Next
End Sub
答案 0 :(得分:1)
尝试以下方面的内容:
Sub Demo()
Application.ScreenUpdating = False
Dim i As Long, j As Long
Const l As Long = 50
With ActiveDocument.Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "<?{" & l - 1 & "}@>"
.Replacement.Text = ""
.Forward = True
.Format = False
.Wrap = wdFindStop
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
i = InStrRev(.Text, " ") - 1
If (Len(.Text) - l) > (Len(.Text) - i) / 2 Then
.Start = .Start + i
.Collapse wdCollapseStart
j = j + i
Else
j = j + Len(.Text)
End If
.Collapse wdCollapseEnd
.InsertBefore " _@@@_" & j & "_@@@_"
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub
其中变量l是所需的间隔。
答案 1 :(得分:1)
对于较大的间隔,请尝试:
ValueError