I needed a function that would conveniently return me a Range that contained the top of the next page in a Word document.

The following does the trick:

Function TopOfNextPage(rng As Word.Range) As Word.Range
    Set TopOfNextPage = rng.Duplicate.GoTo(What:=wdGoToPage, Which:=wdGoToNext)
End Function 

Notice it does not disturb the original Range. It accomplishes this by use of the Range.Duplicate function, which I find very handy sometimes when I don’t want to disturb my original Range.

Notice the returned Range is collapsed to the top of the page.

 

Here’s a handy little function that tells you if the end of a Range in Word VBA lies on the last page of the document:

Function IsLastPage(rng As Word.Range) As Boolean
     IsLastPage = CBool(rng.Information(wdActiveEndPageNumber) = rng.Information(wdNumberOfPagesInDocument))
End Function 

The Range.Information function is very useful. Check it out!

We hope it comes in handy.

 

I wanted a function in Word VBA that would add a Field to a Range’s Fields collection and automatically extend the Range to include the added field.

This mimics the behavior of the Range.InsertAfter function and similar functions.

It allows you to keep adding text, fields, and other items to a Word document sequentially.

The function I created is called InsertFieldAfter. Its parameters mimic the parameters to the Fields.Add function.

The Range you pass in is extended to include the newly added Field. The new Range is also returned as the function return value for convenience.

The text of the function and related support functions is below, followed by an example of how to use the function.

' Expand the Range to include the added field and return it. Public Function InsertFieldAfter( _
             ByRef Range As Word.Range, _
             ByVal FieldType As WdFieldType, _
             ByVal Text As String, _
             Optional ByVal PreserveFormatting As Boolean = False _
         ) As Word.Range
     On Error GoTo handler
     Dim StartPos As Long, EndPos As Long
     StartPos = Range.Start
     Range.Collapse Direction:=wdCollapseEnd
     EndPos = Range.Fields.Add( _
             Range:=Range, _
             Type:=FieldType, _
             Text:=Text, _
             PreserveFormatting:=PreserveFormatting) _
         .Result.End + 1
     Range.SetRange StartPos, EndPos
     Set InsertFieldAfter = Range
     Exit Function
handler:
     ' handle any run-time error here
End Function 

Here’s a code snippet showing an example of its use:

With myRange
     .InsertAfter "Here is a field: "
     InsertFieldAfter Range:=myRange, FieldType:=wdFieldEmpty, Text:="REF Field1"
     .InsertAfter vbCrLf & "Here is another field: "
     InsertFieldAfter Range:=myRange, FieldType:=wdFieldEmpty, Text:="REF Field2"
     .InsertAfter vbCrLf
End With 

Happy coding!

© 2011 Soundside Software Suffusion theme by Sayontan Sinha