0

I have defined a message function to put different messages in it. That means when I call this function in a form, then just the corresponding chosen message has to display on the screen. Here my example:

'Thats the message sub
Public Sub MsgString(txtNo As Byte)
    MsgBox MsgTxt(txtNo)
End Sub

'Thats the message function to return the corresponding value, which is chosen
 Private Function MsgTxt(txtNo As Byte) As String
     Dim arrMsgTxt() As Variant
     arrMsgTxt = Array("error message number one", "error message number two", "error message number three")

     For txtNo = LBound(arrMsgTxt) To UBound(arrMsgTxt)
            MsgTxt = arrMsgTxt(txtNo)
            Exit Function
     Next txtNo
 End Function

Is there a better way to solve it? Currently, I need to exit the function after the instantiated value.

3
  • Why would you need to loop through the array of error messages if you know (presumably by the value of txtNo) which one of the messages you want to use? You could drop the For and Next lines, along with the Exit Function and have no change to the functionality Commented May 18, 2016 at 11:57
  • @Dave Yes, the variable txtNo contains the number in the array. Do you have an idea for a better solution? Commented May 18, 2016 at 12:01
  • See Gary's Student's answer... Commented May 18, 2016 at 12:02

1 Answer 1

2

The usual way to to pass an index to the UDF. That way, you don't need a loop:

Public Function TellMe(indx as Long) as String
    ary = Array("Mike", "James", "Paul", "William")
    TellMe = ary(indx)
End Function

Sub MAIN()
    MsgBox TellMe(2)
End Sub

Remember, the default indexing is zero-based............so expect "Paul"

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I had this defined before and had a strange error message, however, now it works :)
@yuro Thank you for the feedback!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.