1

我是 VBA 新手,我需要帮助。我想创建以表名作为输入的 vba 函数,并从该表中区分特定字段。我创建了函数,当我在 vba 即时窗口中运行它时它可以工作(当我使用 debug.print 命令显示结果时)。但是当我在 sql 中调用这个函数,而不是整个字段值时,它只返回最后一个。我不擅长 vba 语法,所以我需要帮助来理解。函数可以返回多个值吗?如果可以,如何,如果不能,还有什么可以使用?这是我的代码:

Public Function TableInfo(tabela As String)
Dim db As Database
Dim rec As Recordset
Dim polje1 As Field, polje2 As Field
Dim sifMat As Field, pogon As Field, tipVred As Field

Set db = CurrentDb()
Set rec = db.OpenRecordset(tabela)
Set sifMat = rec.Fields("Field1")
Set pogon = rec.Fields("Field2")
Set tipVred = rec.Fields("Field3")

For Each polje1 In rec.Fields
    For Each polje2 In rec.Fields
        TableInfo = pogon.Value
        rec.MoveNext
    Next
Next

End Function

任何帮助表示赞赏。

4

2 回答 2

1

问题可能出在这条线上:

TableInfo = pogon.Value

它在循环内运行并返回循环的最后一个值。

TableInfo您可以尝试返回类似于 aCollection或 an 的东西,而不是返回一个值Array

在循环内部,在 Collection 中附加值,在循环之后,从函数返回 Collection。

编辑:

我重写了你分享的代码:

Public Function TableInfo(tabela As String) as String()
    Dim db As Database
    Dim rec As Recordset
    Dim polje1 As Field, polje2 As Field
    Dim sifMat As Field, pogon As Field, tipVred As Field

    Dim returnValue() As String
    Dim i as Integer

    Set db = CurrentDb()
    Set rec = db.OpenRecordset(tabela)
    Set sifMat = rec.Fields("Field1")
    Set pogon = rec.Fields("Field2")
    Set tipVred = rec.Fields("Field3")

    ' I am not going to modify this but I think we can do away with two For Each loops.
    ' Just iterate over rec like
    ' For Each r In rec -> please use proper naming conventions and best practices
    ' and access each field as r("Field1") and r("Field2")
    For Each polje1 In rec.Fields
        For Each polje2 In rec.Fields
            returnValue(i) = pogon.Value
            i = i + 1
            rec.MoveNext
        Next
    Next
    TableInfo = returnValue
End Function

请注意:我没有测试过这段代码,但我认为这应该适合你。另外,我假设您要返回String()数组。如果要返回其他类型,请更改数据类型。

于 2013-08-21T12:13:23.163 回答
0

When you call the array (as posted in theghostofc's answer), you will need to do something like this:

Dim TableInfo() As String

For i = LBound(TableInfo) To UBound(TableInfo)
  YourValue = TableInfo(i)
  ... Process some code that uses YourValue
Next i

If you're not looping through your array, you're not going to get each individual value out of it.

于 2013-08-21T13:55:55.800 回答