2011-11-12 29 views
0

所以,我有一個ValidateForm函數,它循環通過表單來驗證每個控件。我有一個名爲ValData的集合,用於捕獲從函數中傳出的不同信息。這很好。從自定義函數返回多個值

但是,我不知道如何在函數返回後訪問ValData中的每個項目。我一次可以得到一個:ValidateForm()。IsValid,但爲了獲得每個項目,我必須再次運行該函數。我想避免這種情況。

有沒有辦法運行一次函數,但訪問返回的每個項目的值?

+1

顯示您的當前代碼 –

回答

2

根據您的要求(這不是你的問題清楚;-)!),你可以考慮使用一個集合作爲從函數的返回:

Private Function MyResultsFunction() As Collection 
    Dim output As Collection 
    Set output = New Collection 

    'Hydrate your collection with data by whatever means necessary: 
    With output 

     'Stupid example code: 
     .Add "Item1" 
     .Add "Item2" 
     .Add "Item3" 
     .Add "Item4" 
    End With 

    'Return a reference to the collection as the function output: 
    Set MyResultsFunction = output 

End Function 

作爲一個簡單,弱智以上測試:

Private Sub Form_Load() 

    'A variable to receive the results from your function: 
    Dim Results As Collection 

    'An iterator to loop through the results contained in the collection: 
    Dim CurrentItem As Variant 

    'For this example, a string to toss the results into to display in the 
    'MsgBox: 
    Dim output As String 

    'Use the local Collection defined above to access the reference returned by 
    'your function: 
    Set Results = MyResultsFunction 

    'Iterate through the collection and do something with the results 
    'per your project requirements: 
    For Each CurrentItem In Results 

     'This is stupid example code: 
     output = output & CurrentItem & vbCrLf 
    Next 

    'I am just displayng the results to show that it worked: 
    MsgBox output 

    'Clean up: 
    Set Results = Nothing 

End Sub 

希望heps!

0

沒有看到你的代碼,很難說你正在做什麼,但這裏有幾種方法可以存儲結果以供日後查詢。

在模塊的頂部聲明一個公共變量來表示ValData函數中的項目。填充數組後,可以通過普通函數訪問這些項目。

你顯然可以做更復雜的事情,特別是如果你使用集合對象。你甚至可以存儲一個計數器並創建一個GetNext()函數。我希望這給你一個開始。

Public Results(1 To 2) As String 

Sub CreateTestArray() 
    Results(1) = "Foo" 
    Results(2) = "Bar" 
End Sub 

Function GetResult(ByVal i As Long) As String 
    If i <= UBound(Results) Then 
     GetResult = Results(i) 
    End If 
End Function 

Sub ProofOfConcept() 
    MsgBox GetResult(2) ' will show "Bar" 
End Sub