所以,我有一个ValidateForm函数循环一个表单来验证每个控件。我有一个名为ValData的集合设置,用于捕获要从函数中传出的不同信息位。这很有效。
但是,我不知道在函数返回后如何访问ValData中的每个项目。我可以一次得到一个:ValidateForm()。IsValid,但为了得到每个项目,我必须再次运行该函数。我想避免这种情况。
有没有办法运行一次该函数,但访问返回的每个项的值?
答案 0 :(得分:2)
根据您的要求(在您的问题中不明确!;-)),您可以考虑使用Collection作为函数的返回值:
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
希望嘻嘻!
答案 1 :(得分: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