2011-11-12 30 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