PDA

View Full Version : Return all text from non contiguous selection



stevebayliss
10-11-2017, 07:16 PM
Hi All,

If a non-contiguous range is selected, the command Selection.Text will only return the last block of text added to the selection. I need to be able create a string that contains all the text that has been selected. As an added step I would also ideally like the string to also include some delimiter (space, return, comma) between each of the selected blocks so in this example assume that a user selects the text 'brown' and 'lazy dog' from the text below:

'the quick brown fox jumped over the lazy dog'

Then I would need a to have a string returned something like 'brown lazy dog'

Interestingly the command:

Selection.Copy would copy all the selected text but Selection.Text only returns the last block, in the case of the above example 'lazy dog'

Thanks

Steve Bayliss
STEOLA

macropod
10-11-2017, 11:56 PM
Perhaps:

Sub Demo()
Dim DocTmp As Document, StrTmp As String
Selection.Copy
Set DocTmp = Documents.Add(Visible:=False)
With DocTmp
With .Range
.Paste
StrTmp= Split(Replace(Replace(.Text, vbCr, " "), " ", " "), vbCr)(0)
End With
.Close False
End With
Set DocTmp = Nothing
MsgBox StrTmp
End Sub

stevebayliss
10-12-2017, 12:26 AM
Thanks Paul,

I appreciate you replying.

So there is no way to identify each individual block that is selected?

Is there any other way than using the clipboard? I dont want to overwrite that if there is already something there.

What I don't understand is how selection.copy or selection.font... can work on the full text yet there doesn't seem to be a way to return that text?? seems bizarre there is not a way to easily get the full text or even concatenate the ranges into a single string..

I was was initially looking for something like selection.areas() like excel would expose. ..

i am not over familiar with the Word object model, could I do a .find on the selection using a wildcard to return all the text or something??

If I can't do that I may utilize the clipboard and reset it back to its ogininal value after getting the selection text.




Thanks Steve

macropod
10-12-2017, 12:37 AM
The mere fact you can do something via the GUI doesn't mean there's a VBA equivalent. Word isn't Excel, either.

Sure you can identify each selected block. Indeed, that's something I had to address for the code I posted, via:
Split(Replace(Replace(.Text, vbCr, " "), " ", " "), vbCr)(0)
but that's because of how you said you wanted the output represented!!! If I'd used just:
StrTmp = .Text
each 'block' would start on a new line in the message box.