开发者

inserting a numbered item

Say I have a word document that contains a keyword followed by a number such as the following.

function_1 : This is a the first f开发者_JAVA技巧unction, and usually the next function is the second function. How do I increment the next function. function_2 : This is the second function. Here I stop.

How do I create a macro that would search through the whole word document, determined that the next number is function_3, and inserted function_3 into the document as the current cursor position.


Try this:

Public Sub Test1()
    On Error GoTo MyErrorHandler

    Dim sourceDocument As Document
    Set sourceDocument = ActiveDocument

    Dim findRange As Range
    Set findRange = sourceDocument.Range
    findRange.Find.ClearFormatting
    findRange.Find.MatchWildcards = True

    Dim functionNumber As String
    Dim largestNumber As Long
    largestNumber = -1
    Do While findRange.Find.Execute(findtext:="function_[0-9]{1,} :") = True
        'findRange.Select

        functionNumber = Left$(findRange.Text, Len(findRange.Text) - 2)
        functionNumber = Mid$(functionNumber, 10)

        If functionNumber > largestNumber Then largestNumber = functionNumber

        DoEvents
    Loop

    sourceDocument.Range.InsertAfter "function_" & largestNumber + 1 & " :"

    Exit Sub

MyErrorHandler:
    MsgBox "Test1" & vbCrLf & vbCrLf & "Err = " & Err.Number & vbCrLf & "Description: " & Err.Description
End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜