【问题标题】:Save .Find() function results to array Excel VBA将 .Find() 函数结果保存到数组 Excel VBA
【发布时间】:2015-09-15 09:06:34
【问题描述】:

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

【问题讨论】:

    标签: arrays excel vba


    【解决方案1】:

    查看您如何将数组重新调整为 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
    

    【讨论】:

    • 我不敢相信。我改为键入 ReDim myArray(0 To i),我键入了 ReDim myArray(0, i)。它现在可以工作了,感谢您的帮助,对于愚蠢的问题,我们深表歉意。
    • @mathsicist - 哈哈,这发生在我们最好的人身上。从那以后,我投资了一个rubber ducky,他会在这种时候提供帮助。 :P(如果有效,介意标记为答案吗?)
    猜你喜欢
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2010-09-05
    • 2016-06-23
    • 1970-01-01
    • 2016-03-11
    • 1970-01-01
    相关资源
    最近更新 更多