将.Find()函数结果保存到数组Excel VBA

时间:2015-09-14 17:33:55

标签: arrays excel-vba vba excel

我想将包含该字符串的所有找到的行数保存到数组中。我写了一个正常工作的函数,但我无法将其结果保存到数组中。我可能会把它保存为.Row值但是.Address作为字符串然而它不是我的目标。我尝试将数组类型从整数更改为长整数,但这不起作用。你知道我应该怎么做吗?什么是价值类型。如何?通过手动.Find()函数返回Range类型,但我不确定.Row值是否也是Range。如果是如何利用这些知识来解决问题? 我的代码:

Function findTesterRows(przypisFileName As String, testerName As String, tableSize As Integer) As Integer()
Dim tableRange As String
    tableRange = "A2:L" & tableSize
Dim myArray() As Integer
Dim i As Integer
    i = 0

With Workbooks(przypisFileName).Worksheets("Sheet1").Range(tableRange)
    Set foundRow = .Find(What:=testerName, LookIn:=xlValues)
    If Not foundRow Is Nothing Then
        firstAddress = foundRow.Address
        Do
            i = i + 1
            Set foundRow = .FindNext(foundRow)
        Loop While Not foundRow Is Nothing And foundRow.Address <> firstAddress
    End If
End With

ReDim myArray(0, i)
i = 0

 With Workbooks(przypisFileName).Worksheets("Sheet1").Range(tableRange)
    Set foundRow = .Find(What:=testerName, LookIn:=xlValues)
    If Not foundRow Is Nothing Then
        firstAddress = foundRow.Address
        Do
            MsgBox foundRow.Row
            myArray(i) = foundRow.Row '!!HERE IS THE PROBLEM!!
            i = i + 1
            Set foundRow = .FindNext(foundRow)
        Loop While Not foundRow Is Nothing And foundRow.Address <> firstAddress
    End If
End With

findTesterRows = myArray

End Function

1 个答案:

答案 0 :(得分:2)

查看如何将数组重新定位到ReDim myArray(0,i)。然后看看你以后如何调用它myArray(i) = foundRow.Row

缺少第二个索引。尝试myArray(0,i) = foundRow.Row

然后,要返回所有的行,您可以执行类似

的操作
for i = lbound(myArray) to ubound(myArray)
 debug.print "Rows are: " & myArray(0,i)
next i