PDA

View Full Version : Determine the extent of the text that has just been inserted in vba



p45cal
06-30-2014, 08:18 AM
Say I have just used vba code to insert some plain text into the middle of a document (by using a placeholder bookmark, or a range variable, or less likely, a selection related location), now I want further to manipulate the newly inserted text in vba.
1. Is there a 'best-practice' or method of choice to refer to the newly inserted text.
2. Would the same method be used to identify the range having pasted from Excel using the likes of .PasteExcelTable?

macropod
06-30-2014, 05:44 PM
I'd define the range, then add text to it and use the range for any further manipulations of that text. For example:

Sub Demo()
Dim Rng As Range
With ActiveDocument
Set Rng = .Sections.First.Range.Tables(1).Range.Cells(1).Range.Paragraphs(1).Range.Ch aracters.Last
With Rng
.Collapse wdCollapseStart
.Text = "Hello World"
With .Words.First.Font
.Bold = True
.ColorIndex = wdPink
End With
With .Words.Last.Font
.Italic = True
.ColorIndex = wdBrightGreen
End With
End With
End With
End Sub

p45cal
07-01-2014, 07:52 AM
Thankyou for this macropod, I'll try to use this in the thread: http://www.vbaexpress.com/forum/showthread.php?49977-Excel-VBA-Open-Word-template-and-create-bulleted-list-based-on-cell-values where I found the process of formatting inserted text to be more convoluted than I would want/expect.