Hi Ryan,
An unfortunate problem with Word's wildcard feature is that there's no way
to say "zero or more of this character"; the best you can do is "one or
more". That makes things a bit more complicated, because you can't search in
one step for a $ followed by zero or more spaces followed by a number.
Here's what's necessary to deal with spaces between the $ and the numbers:
- Add a space character to the list of characters in square brackets in the
..Text expression:
.Text = "$[0-9,. ]@"
This will find a $ followed by *any* sequence of digits, commas, periods,
and spaces. The spaces could be before the numbers, after the numbers, or
even between the numbers.
- Add the Trim function in the "remove $" statement:
strNumbers = Trim(Right( _
strNumbers, Len(strNumbers) - 1))
This removes any spaces to the left of the first digit or to the right of
the last digit/comma/period
- This part is optional... With the new search expression, your code could
find two numbers separated by one or more spaces, like $ 225.00 234 .
If you're worried about that, add the following lines between the "remove $"
and the "return value":
Dim SpacePos As Long
SpacePos = InStr(strNumbers, " ")
If SpacePos > 0 Then
strNumbers = Left(strNumbers, SpacePos - 1)
End If
This will chop off the first remaining space and anything that follows it.
--
Regards,
Jay Freedman
Microsoft Word MVP
Ryan said:
Hey, thank a lot! You code works as advertised.
One thing is that it finds the value but most of the time. Sometimes
it doesn't get the value or overlooks the value. Might be because
there are several spaces in between the dollar sign and the dollar
value in some cases, so it could be like:
$ 225.00
The problem is that some (most) of these values are getting picked up
(found) while some others are not. Could it have to do with the
document formatting? Any ideas? Here's the function as of right now:
Function FindLastAmount(WordDoc As Word.Document) As String
Dim strNumbers As String
Dim oRg As Word.Range
Set oRg = WordDoc.Application.ActiveDocument.Range
'trying some stuff here
oRg.Select
WordDoc.ActiveWindow.Selection.ClearFormatting
' start at end of document
oRg.Collapse Direction:=wdCollapseEnd
With oRg.Find
.ClearFormatting
.MatchWildcards = True
.Text = "$[0-9,.]@"
.Forward = False ' search backward
.Format = False
.Wrap = wdFindStop
If .Execute Then
strNumbers = oRg.Text
Do While Right(strNumbers, 1) = ","
strNumbers = Left( _
strNumbers, Len(strNumbers) - 1)
Loop
' remove $
strNumbers = Right( _
strNumbers, Len(strNumbers) - 1)
'return value
FindLastAmount = strNumbers
End If
End With
End Function
'Courtesty of Jay Freedman Microsoft, Word MVP - FAQ:
http://word.mvps.org
Thanks again!
- Ryan