繁体   English   中英

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

[英]Save .Find() function results to array Excel VBA

我想将包含字符串的所有找到的行数保存到数组中。 我编写了一个功能正常的函数,但是无法将其结果保存到数组中。 我可能不会将它保存为.Row值,而是将.Address保存为字符串,但这不是我的目标。 我尝试将数组类型从整数更改为long,但这不起作用。 你知道我该怎么办吗? 值行的类型是什么? 通过手动.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

查看如何将数组重新定义为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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM