Switch function, If Then, or Select Case? (or something else?)

B

Benjamino5

I need to write a function which checks for certain strings in a field, then
reports back a "field type" (my term, not the actual fieldtype in Word) based
on the strings it finds. I don't know quite how to write this. Here's what I
have so far:

Function FieldType(oField As Field) As String
FieldType = Switch((InStr(oField.Code, "mNL1")), "mNL1", (InStr(oField.Code,
"mNLa")), "mNLa", _
(InStr(oField.Code, "MACROBUTTON")), "TypeHere")
End Function

The problem is that if none of the expressions in the Switch function are
true, there's an error. I'd like to add an "OTHER" string that the function
would produce if the field it checks isn't any of my "types" (mNL1, mNLa, and
TypeHere). How would I do that?

Should I be using something other than the Switch function? I thought of
using a Select Case statement, but I'm not sure how to phrase the InStr
checks as a single expression that could be evaluated for each case.

I feel like the answer is staring me in the face, but I'm not familiar
enough with programming to know what I should do. Thanks for any advice you
can give me!
 
J

Jay Freedman

Try it this way:

Private Function FieldType(oField As Field) As String
Dim retval As String, code As String
retval = "" ' the default, but be explicit
code = LCase(oField.code) ' use LCase to remove case sensitivity

If InStr(code, "mnl1") Then
retval = "mNL1"
ElseIf InStr(code, "mnla") Then
retval = "mNLa"
ElseIf InStr(code, "macrobutton") Then
retval = "TypeHere"
End If
' otherwise retval is still ""

FieldType = retval
End Function

Sub test()
Dim ft As String
ft = FieldType(ActiveDocument.Fields(1))
If ft <> "" Then
MsgBox ft
Else
MsgBox "None of the above"
End If
End Sub

--
Regards,
Jay Freedman
Microsoft Word MVP
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
 
B

Benjamino5

Jay, thank you very much! I'll use that code with very few changes in my
project.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top