Microsoft Word - Selecting some text in a table cell via VBA/Macro

Asked By Reuben Helms on 04-May-10 11:33 PM
Hi

I'm trying to write some Word VBA to select some text in a table cell.  The selection is to start from the first instance of a paragraph marker in the cell, and extend to the end of cell marker. 

The idea is that I might have a cell with CellLine1^pCellLine2^pCellLine3 and want to cut all text from the first paragraph marker to the end of the cell, leaving only the first line.

So far, I have:

aCell.Select
With Selection.Find
    .Text = "^p"
    .Forward = True
    .Wrap = wdFindStop
End With
Selection.Find.Execute
If Selection.Find.Found = True Then
    With Selection
        .StartIsActive = False
        .EndOf Unit:=wdCell, Extend:=wdExtend
        .MoveEnd Unit:=wdCharacter, Count:= -1
 
        .Cut
    End With
End If

The finding of the paragraph marker is fine, but when the selection moves to the end of the cell, the whole cell is selected, and I lose the start marker at the beginning of the paragraph mark.

I've trying using .MoveStartUntil("^p") after the move end to move the selection to the start of that first paragraph marker, but that didn't seem to work.

Any pointers?
al replied to Reuben Helms on 05-May-10 06:15 PM
This should fix your problem

acell.Select
strtext = Selection.Text

With Selection.Find
    .Text = "^p"
    .Forward = True
    .Wrap = wdFindStop
End With
Selection.Find.Execute

If Selection.Find.Found = True Then
       With Selection
        .StartIsActive = False
        '.EndOf Unit:=wdCell, Extend:=wdExtend
        .MoveRight Unit:=wdCharacter, Count:=(Len(strtext) - InStr(strtext, vbCr) - 2), Extend:=wdExtend
        .Select
        .Cut
       End With
    extract_String = Mid(strtext, InStr(strtext, vbCr) + 1)
   
End If

You subtract an additional 2 bytes from the length because you have to start past the first carriage control and then you stop before the last return.

VbCr is a constant that is the equivalent of a carriage return.