PDA

View Full Version : [SLEEPER:] Find string in Word document



lebowski
10-31-2014, 03:45 AM
I am simply trying to find text in a Word document using a string. I have the following code:



Dim mystring As String
Selection.WholeStory
Selection.Find.ClearFormatting
With Selection.Find
.Text = mystring
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchFuzzy = False
End With
Selection.Find.Execute

The variable 'mystring' has been populated earlier in the code and exactly matches the text in the document. Nothing happens on running the code.

If I add exactly the same text to the string before running the code, it works fine:



Dim mystring As String
mystring = "text marker"
Selection.WholeStory
Selection.Find.ClearFormatting
With Selection.Find
.Text = mystring
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchByte = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = False
.MatchFuzzy = False
End With
Selection.Find.Execute

There has to be something simple that I am missing. Any help would much appreciated. Thanks.

lebowski
10-31-2014, 04:57 AM
I found the reason. I had included text in the string from a selected table cell in Word. I thought this added an unwanted character at the end of the string, so had removed the last character. It turns out that there are 2 characters that need to be removed from the end of the string when selecting text this way.

Does anyone know how to copy the contents of a Word table cell into a string without selecting the entire cell (Selection.SelectCell), thus avoiding appending the text with these unwanted characted?

Dave
10-31-2014, 06:34 AM
Left(yourtablecell,Len(yourtablecell)-2)
HTH. Dave

gmayor
10-31-2014, 07:22 AM
Dim oRng As Range
Dim strCellText As String
Set oRng = Selection.Cells(1).Range
oRng.End = oRng.End - 1
strCellText = oRng.Text

snb
10-31-2014, 11:05 AM
Sub M_snb()
MsgBox Replace(Tables(1).Cell(1, 1).Range, vbCr & Chr(7), "")
end sub

Tommy
10-31-2014, 01:08 PM
another way

Sub Look() Dim ask As String
With ActiveDocument.Tables(1)
ask = Replace(.Cell(2, 2).Range.Text, vbCr & Chr(7), "")
End With
End Sub