2016-05-18 87 views
0

我已經定義了一個消息函數來在其中放入不同的消息。這意味着當我在窗體中調用此函數時,只需在屏幕上顯示相應的選定消息。這裏我的例子:從VBA中的數組中返回值

'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 

有沒有更好的方法來解決它?目前,我需要在實例化的值之後退出函數。

+0

爲什麼如果您知道(想要通過txtNo的值)您想要使用哪條消息,您是否需要遍歷錯誤消息數組?您可以刪除For和Next行以及Exit Function,並且不會更改功能 – Dave

+0

@Dave是的,變量'txtNo'包含數組中的數字。你有一個更好的解決方案的想法嗎? – yuro

+0

查看Gary的學生回答... – Dave

回答

2

索引傳遞給UDF的常用方法。這樣,你不需要一個循環:

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 

記住,默認的索引是從零開始的............所以我們期待「保羅」

+0

謝謝。我之前定義過這個,並且有一個奇怪的錯誤消息,但是,現在它可以工作:) – yuro

+0

@yuro感謝您的反饋! –