访问由VBA宏函数返回的数组

时间:2014-03-31 12:15:47

标签: excel vba excel-vba

我想知道如何访问函数返回的数组的值。 据我所知,返回的值应该具有相同的函数名称。

Function PathFinder(sheet1 As String, word1 As String) As Integer()
Dim rng As Range
Dim rngFound As Range
Dim temp(1, 2)

Set rng = Sheets(sheet1).Range("A:D")
Set rngFound = rng.Find(word1, LookAt:=xlWhole)

If rngFound Is Nothing Then
    MsgBox "not found"
Else:
     temp(1, 1) = rngFound.Row
     temp(1, 2) = rngFound.Column

     PathFinder = temp
End If

End Function

这已经完成,我没有找到如何访问值“PathFinder(1,1)”和“PathFinder(1,2)”

提前感谢您的帮助

2 个答案:

答案 0 :(得分:0)

我会这样做:

Function PathFinder(sheet1 As String, word1 As String) As Long()
    Dim rng As Range
    Dim rngFound As Range
    Dim temp(1, 2) As Long

    Set rng = Sheets(sheet1).Range("A:D")
    Set rngFound = rng.Find(word1, LookAt:=xlWhole)

    If rngFound Is Nothing Then
        MsgBox "not found"
    Else
        temp(1, 1) = rngFound.Row
        temp(1, 2) = rngFound.Column
    End If
    PathFinder = temp
End Function

Sub test()
    Dim res() As Long

    res = PathFinder("Sheet1", "A")
    MsgBox "Row:" & res(1, 1) & " Column: " & res(1, 2)
End Sub

另请注意,我稍微更改了您的PathFinder功能。

  • 我已将PathFinder = temp移至最后。原因很简单:如果在您的版本行MsgBox "Row:" & res(1, 1) & " Column: " & res(1, 2)中找不到任何内容会触发错误,但在我的版本中,您会获得"魔术数字"如果找不到任何内容,即它返回0行和列。
  • 我已将回复类型从Integer()更改为Long(),因为Integer的最大值仅为32768,有时您可能会出现溢出错误(自{{ 1}}可能大于rngFound.Row)。

答案 1 :(得分:0)

该函数返回数组,所以:

Dim arr() as Integer
arr = PathFinder("sheet","word")

Debug.Print arr(1,1)
Debug.Print arr(1,2)    

我建议删除二维数组(temp):

Function PathFinder(sheet1 As String, word1 As String) As Integer()
Dim rng As Range
Dim rngFound As Range
Dim temp(2) As Integer

Set rng = Sheets(sheet1).Range("A:D")
Set rngFound = rng.Find(word1, LookAt:=xlWhole)

If rngFound Is Nothing Then
    MsgBox "not found"
Else:
     temp(1) = rngFound.Row
     temp(2) = rngFound.Column
End If

PathFinder = temp

End Function

Public Sub Test()
    Dim arr() As Integer
    arr = PathFinder("sheet1", "1word")

    If arr(1) = 0 Then
        Debug.Print "not found"
    Else
        Debug.Print arr(1)
        Debug.Print arr(2)
    End If
End Sub