MS Word Macro to increment all numbers in word document

烂漫一生 提交于 2019-11-29 17:44:43
ZolVas

There is another option. I hope you are familiar with the concept of arrays (in any language). Just keep in mind that in VBA arrays are inside brackets ("[1]", "[2]"). If not, it won't be a problem.

If your goal is to replace [1] for [11], [2] for [12], ... [n] for [n+10] then you may do the following.

Please, consider to look here. The answers are alike. Changing numbering in word using VBA

The concept is to work with two arrays two times: I) replace [1] for @@@[1]@@@, [2] for @@@[2]@@@, ..., [n] for @@@[n]@@@; II) replace @@@[1]@@@ for [11], @@@[2]@@@ for [12], ..., @@@[n]@@@ for [n+10].

More profound view:

1.1) Create searchArray from [1] to [n]. You can use this. http://textmechanic.com/generate-list-numbers/. Prefix numbers with: "[", suffix with: "]", Join with: ",".

1.2) With the same tool create replaceArray with prefix "@@@" and sufix "@@@" (for uniqueness), i.e. @@@[1]@@@, @@@[2]@@@, .. @@@[n]@@@.

1.3) Replace searchArray for replaceArray.

[Adapt code from Annex].

2.1) Create searchArray, it is the same as in 1.2)

2.2) With the tool http://textmechanic.com/generate-list-numbers/ create replaceArray from [10] to [n+10]. I.e. [10], [11], ... [n]

2.3) Replace searchArray for replaceArray.

[Adapt code from Annex].

Annex

Option Explicit
Sub replaceArrayForArray()
'
'to create array use prefix\suffix and replacing tool http://textmechanic.com/
'
'
findArray = Array("[1]", "[2]", "[3]")
replArray = Array("@@@[1]@@@", "@@@[2]@@@", "@@@[3]@@@")

For i = 0 To UBound(findArray)
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    With Selection.Find
        .Text = findArray(i)
        .Replacement.Text = replArray(i)
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute replace:=wdReplaceAll
Next i
End Sub

PS: Why not replace [1] for [11]? But we have to firstly replace [1] for @[1]@ and then secondly @[1]@ for [11]?

Because in 10 iterations through loop we will have two [11] that will both turn into [21]; then three [21] that will turn into [31] etc.

PPS: Both parts of the code if you'd like to copy and paste the answer: http://codepad.org/sZEG78ak. But still you will have to expand arrays as noted above.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!