将2个数组与行的值匹配

时间:2019-04-28 17:38:24

标签: excel vba

我想编写一个代码,该代码使用两个1D数组,并基于与该行上的值的匹配,它应返回第3个数组中的值。

这就是我想要做的:

在Sheet1中,我有3列,其中包含有关ID,名称和金额的数据,其中许多行的大小不确定: enter image description here

在Sheet2中,我已经有带有ID和Name数据的列,但没有Amount数据:

enter image description here

因此,我想运行将匹配Sheet1中ID和Name数据与Sheet2中ID和Name数据的数组匹配的代码,然后将相应的Amount数据返回到Sheet2中。

这是运行代码后在Sheet2中理想的结果,即根据与Sheet1中ID和Name上的数组的匹配返回Amount列中的数据: enter image description here

这是我的代码无法正常运行:

cc=sorted(chicago_crime['neighborhood'].unique())
ho=sorted(house_df['neighborhood'].unique())

print(30*u"-"+u" chicago_crime: "+30*u"-")
print(len(cc),cc)
print(30*u"-"+u" house_df: "+30*u"-")
print(len(ho),ho)
print(60*"-")
# print('\n'.join(cc))

set1 = set(cc)
set2 = set(ho)

missing = list(sorted(set1 - set2))
added = list(sorted(set2 - set1))

print('These {0} are missing in house_df: {1}'.format(len(missing),missing))
print(60*"-")

print('These {0} are only in house_df: {1}'.format(len(added),added))

我的代码没有返回任何内容,我可以假设这是因为我正在将sheet1中的数组与sheet 2中的行进行比较,这在大小上没有可比性,但是我不知道该怎么做。 我将不胜感激。

1 个答案:

答案 0 :(得分:0)

只需修改您的代码,使其包含一个内部循环即可检查w_output表中的ID和名称(也可以使用Find完成)。经过临时数据测试。但是,还有其他(更有效的)方法可以实现相同的目标。

Sub ArrayMatch()

Dim r As Long
Dim d As Long
Dim w_output As Worksheet
Dim w1 As Worksheet
Dim intLastRow As Long            ' Modified to long
Dim IntLastRow1 As Long           ' Modified to long
Dim arrName() As Variant
Dim arrID() As Variant
Dim arrrAmoun() As Variant

'd = 8

With ThisWorkbook
    Set w1 = .Sheets("Sheet1")
    Set w_output = .Sheets("Sheet2")
End With

'***********************************
'Assign arrays

With w1

    intLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    IntLastRow1 = w_output.Cells(Rows.Count, 1).End(xlUp).Row
    arrID = .Range(.Cells(4, 1), .Cells(intLastRow, 1))
    arrName = .Range(.Cells(4, 3), .Cells(intLastRow, 3))
    arrAmoun = .Range(.Cells(4, 4), .Cells(intLastRow, 4))

    For r = 1 To UBound(arrID, 1)
        If Len(arrID(r, 1)) > 0 Then
            For d = 9 To IntLastRow1     ' Modified to for loop for w_output sheet
                If w_output.Cells(d, 1) = arrID(r, 1) Then
                    If w_output.Cells(d, 2) = arrName(r, 1) Then
                    w_output.Cells(d, 4) = arrAmoun(r, 1)
                    Exit For            ' added once found and amount  put in place
                    End If
                End If
            Next
        End If
    Next r

End With

End Sub