访问由VBAmacros函数返回的数组

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

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 

这已经完成,我没有find如何访问值“path查找器(1,1)”和“path查找器(1,2)”

预先感谢您的帮助

该函数返回数组,所以:

 Dim arr() as Integer arr = PathFinder("sheet","word") Debug.Print arr(1,1) Debug.Print arr(1,2) 

我build议删除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 

我会做这一个:

 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 

另外请注意,我已经稍微改变了你的PathFinderfunction。

  • 我已经将PathFinder = temp移动到了结尾。 原因很简单:如果没有在你的版本行中findMsgBox "Row:" & res(1, 1) & " Column: " & res(1, 2)会触发一个错误,但在我的版本中你会得到“幻数”如果没有发现,即它返回0行和列。
  • 我已经将Integer()返回types更改为Long()因为Integer最大值只有32768 ,有时会出现溢出错误(因为rngFound.Row可能大于32768 )。