遍历数组并根据一个或多个搜索条件返回多行

问题描述 投票:0回答:1

女士们,先生们,下午好,

我是新来的。第一个问题!很棒的地方,在此先感谢!

我整个问题都花了整个下午,我无法解决。所以是时候寻求帮助了:-)

案例:

我正在通过两列(客户名和进程号)遍历ArrayDestination我正在遍历ArraySourceData来查找上述搜索条件的匹配项(发票编号和金额)。

如果存在匹配项,它将被“复制”到数组,并且两个循环一旦完成,结果就会被复制到工作表中。

到目前为止,循环只返回第一个匹配项,效果很好。

如果客户有多个相同的过程号,则循环将忽略该事实,仅返回所有过程号的第一个匹配项。不好:-(

我的b变量看起来有点静态,我尝试用b = b + 1使它振作起来,但是没有用。

我无法找到解决方案。你能帮忙吗?

为简单起见,我没有发布创建数组部件的信息。无论如何,它工作正常。但是如果需要,我可以提供。没问题。

Sub search_loop_arrray()

For a = 2 To UBound(ArraySourceData)
    varCustomerName = ArraySourceData(a, 3)
    varProcessNumber = ArraySourceData(a, 5)

    For b = 2 To UBound(ArrayDestination)
        If ArrayDestination(b, 3) = varCustomerName And ArrayDestination(b, 8) = varProcessNumber Then

            ArrayDestination(b, 9) = ArraySourceData(a, 11)
            ArrayDestination(b, 10) = ArraySourceData(a, 12)


            Exit For
        End If
    Next b
Next a

'transfer data (invoice number and amount) from ArrayDestination to wsDestination (Column 9 and 10)
For a = 2 To UBound(ArraySourceData)
    For b = 9 To 10
        wsDestination.Cells(a, b).Value = ArrayDestination(a, b)
    Next b
Next a

End Sub

02/02/2020

我已经在没有数组的嵌套for循环中重写了您的问题。这段代码绝对完美。我面临的问题是我的源数据中存在重复的进程号。如您在我的示例中看到的,我基本上将“找到并粘贴”已经找到的进程号“巧合”在工作表中。由于我要处理100.000+行和20+列,因此我一直希望将其解析为数组。

我不知道我的“复制到临时巧合页”在数组中是否有意义?

Sub find_invoice()

Dim wsSourceData As Worksheet
Dim wsResults As Worksheet
Dim wsCoincidences As Worksheet

Dim varCustomer As String
Dim varProcessNumber As Long
Dim varInvoiceNumber As Long
Dim varSDlastrow As Integer
Dim varRElastrow As Long
Dim varCIlastrow As Long
Dim varCounterResults As Long

Set wsResults = ThisWorkbook.Sheets("RESULTS")
Set wsSourceData = ThisWorkbook.Sheets("SOURCEDATA")
Set wsCoincidences = ThisWorkbook.Sheets("COINCIDENCES")

varSDlastrow = wsSourceData.Cells(Rows.Count, 1).End(xlUp).Row
varRElastrow = wsResults.Cells(Rows.Count, 1).End(xlUp).Row
varCIlastrow = wsCoincidences.Cells(Rows.Count, 1).End(xlUp).Row

For i = 2 To varRElastrow
    varCustomer = wsResults.Cells(i, 1)
    varProcessNumber = wsResults.Cells(i, 2)

    For j = 2 To varSDlastrow
        If wsSourceData.Cells(j, 1) = varCustomer And wsSourceData.Cells(j, 2) = varProcessNumber Then
            wsResults.Cells(i, 3) = wsSourceData.Cells(j, 3)
            wsResults.Cells(i, 4) = wsSourceData.Cells(j, 4)
            wsCoincidences.Rows(varCIlastrow).EntireRow.Value = wsSourceData.Rows(j).EntireRow.Value
            wsSourceData.Rows(j).EntireRow.Delete
            varCIlastrow = varCIlastrow + 1

            Exit For
        End If

    Next j
Next i

End Sub

[女士们,先生们,下午好,我是新来的。第一个问题!很棒的地方,预先感谢!我整个下午都在处理这个问题,我无法解决。因此,该到了...

arrays excel vba search
1个回答
0
投票

我不确定您的逻辑是否正确。如果您说需要匹配2个参数,并且几个实体可以包含这两个参数,那么除了找到第一个或最后一个匹配项外,我看不到如何做。您不需要第三个参数来区分匹配项吗?

© www.soinside.com 2019 - 2024. All rights reserved.