PDA

View Full Version : test/validate selected text



kobber
07-18-2014, 12:04 AM
Hi everyone,

I'm working on a macro which will take the text N (an abbreviated reference number) selected manually by the user in Doc1, open Doc2, which contains a complete list of referenced information, search for N and present the user with the full and correct reference. The goal is to check information against an authoritative list.

So far so good, but I want to check the initial selection for length and format to avoid people making nonsensical selections.

1. There must be a selection, so:


If Selection.Type <> wdSelectionNormal Then
MsgBox ("Please select a reference number" & vbCrLf & "(example: 123/00) and try again.")
End
Else

2. The selection must be at least 4 characters long, so:


If Len(N) < 4 Then
MsgBox ("Oops. Please try again.")
End
End If

3. It must have the format #/## (number-slash-number-number); there can be between 1 and 3 characters to the left of the slash (so ##/## and ###/## would be okay as well).

I suppose this can be done using wildcards, but i don't know how to get this into code.

A related question: would it be prefereable to assign the variable N right away (N = Selection.Text) before running the tests (as in 2), or should I run the tests directly on the Selection (as in 1)?

Thanks for your help and have a great day!

kobber

kobber
07-18-2014, 01:12 AM
Okay, done a bit of research on wildcards word.mvps.org.

My expression must correspond to the following wildcard description: ([0-9]{1,3})</>([0-9]{2})
or "number 0-9, 1 to 3 occurrences; slash; number 0-9, 2 occurrences".

Now, how to put this into practice ...

kobber
07-18-2014, 03:16 AM
No luck so far with either of these approaches:

N As Range

Set N = Selection.Range
If N.Find.Execute(FindText:="([0-9]{1,3})</>([0-9]{2})") Then
MsgBox ("Eureka!")
End If

N As String

N = Selection.Text
If N = "([0-9]{1,3})</>([0-9]{2})" Then
MsgBox ("Eureka!")
End If

I'd really appreciate some pointers. I suppose I need to define the range and search for any text corresponding to the format, but I'm not sure how to implement it.

Thanks and take it easy!

kobber

gmaxey
07-18-2014, 05:32 AM
There is undoubtedly a regular expression that would work, but this seems to work just a well:


Sub ScratchMacro()
'A basic Word macro coded by Greg Maxey
Select Case True
Case Selection Like "###/##", Selection Like "##/##", Selection Like "#/##"
'Eureka
Case Else
Beep
End Select
End Sub

kobber
07-21-2014, 01:49 AM
Hi gmaxey,

That works beautifully. Thanks very much for the help.

I have another variation of the macro that searches for the references, using a regular expression (in this case ([TC]{1})([ \^~-]{1})([0-9]{1,3})[/]([0-9]{2}), with a letter at the beginning), but your solution is much simpler.

Have a great day.

kobber