比较两个列表/每个列表化合物来自2列

时间:2015-02-16 15:08:10

标签: vba excel-vba excel

假设我有个人登录sheet1和列“A”我的主号码是客户帐号,而在“B”栏中我有他们的子帐号。

在表2中,我收到了相同结构中的帐户和子帐户列表,我需要找到sheet2中的唯一编号,但我在个人登录sheet1中没有。

例如在sheet1中我有

account     sub account

1110000     12

1110000     14

我在sheet2列表中收到了包含:

的列表
account     sub account

1110000     12

1110000     16

在这种情况下,宏应该从sheet2列表中找到1110000 16(帐户相同但子帐户是新帐户)并将其写入sheet1中的下一个空单元格。

我将非常感谢您的帮助,我尝试了匹配和vlookup,但它不起作用。

安德鲁

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是将日志表的帐户和子帐户复制到一个数组中。对sheet2中的帐户和子帐户执行相同操作。然后遍历sheet2中的所有帐户和子帐户,并测试它们是否在日志数组中。如果不将它们复制到一个新帐户数组中。最后将新帐户复制到您的日志表中。在此解决方案的代码下方:

Option Explicit
Option Base 1

Sub CopyNewAccountsInLogSheet()

Dim initial As Range 'range with accounts and sub-accounts in sheet 1
Dim destination As Range 'the range where to add new accounts and sub-accounts in sheet1
Dim myLog() As Variant 'array with accounts and sub-accounts from log sheet
Dim newList() As Variant 'array of accounts and sub-accounts from sheet 2
Dim newAccounts() As Variant 'array of accounts and sub-accounts to add to log sheet
Dim x, y, n As Integer
Dim isInLog As Boolean

Set initial = Worksheets("Sheet1").Range("a1").CurrentRegion 'replace with correct range
Set destination = Worksheets("Sheet1").Range("A" & (initial.Rows.Count + 1)) 'first cell below initial range
myLog = initial.Value
newList = Worksheets("Sheet2").Range("a1").CurrentRegion.Value 'replace with correct range
ReDim newAccounts(UBound(newList, 1), 2)
n = 0

For x = 1 To UBound(newList, 1) 'loop through new list

    isInLog = False 'by default, we assume account + sub-account is not in log sheet

    For y = 1 To UBound(myLog, 1) 'compare with each account + sub-account in log file
        If CStr(myLog(y, 1)) & CStr(myLog(y, 2)) = CStr(newList(x, 1)) & CStr(newList(x, 2)) Then
            isInLog = True
            Exit For
        End If
    Next

    If Not isInLog Then
        n = n + 1
        newAccounts(n, 1) = newList(x, 1)
        newAccounts(n, 2) = newList(x, 2)
    End If

Next

If n > 0 Then destination.Resize(n, 2).Value = newAccounts 'copy new accounts in sheet

End Sub