更改宏匹配工作表中的两个cols以返回整行而不仅仅是匹配

时间:2014-04-30 14:45:52

标签: excel-vba vba excel

我设法通过@simoco改变原始宏:How to apply "found" Macro以匹配不同的表格。

我还需要不仅返回匹配而是返回匹配的整行,这我无法弄清楚该怎么做,因为它返回匹配的单元格字符串,用于所有插入的行单元格中的cols E :o

Sub Main()
Dim wsS As Worksheet, wsT As Worksheet
Dim lastrow As Long, lastrowB As Long
Dim match As Boolean
Dim k As Long
Dim arr, varr, v, a, res

Application.ScreenUpdating = False


Set wsS = ActiveWorkbook.Sheets(1)
Set wsT = ActiveWorkbook.Sheets(2)


    lastrow = wsS.Range("B" & wsS.Rows.count).End(xlUp).Row
    lastrowB = wsT.Range("B" & wsT.Rows.count).End(xlUp).Row

    arr = wsS.Range("B2:B" & lastrow).Value
    varr = wsT.Range("B2:B" & lastrowB).Value

    wsT.Range("E:O").EntireColumn.Insert
    wsT.Range("E1").FormulaR1C1 = "name"


k = 1

ReDim res(1 To lastrowB, 1 To 1)

For Each v In varr
    match = False
    'if value from column D (v) contains in column B
    For Each a In arr
        If a = v Then
            match = True
            Exit For
        End If
    Next a

    If match Then
        res(k, 1) = v
    Else
        res(k, 1) = CVErr(xlErrNA)
    End If
    k = k + 1
Next v

With wsT
    .Range("E2:O" & lastrowB).Value = res
End With

Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

要返回v引用的工作表2中的行,如果匹配= TRUE,请在res(k, 1) = v之后插入以下行:

  myRowResult = wsS.Rows(k + 1)

这会将myRowResult设置为整行。您需要在此处执行k + 1,因为您的工作表有标题,但k从1开始。换句话说,如果您只是wsS.Rows(k),那么您将获得该行上方的行匹配。

然后,您可以根据需要在代码中使用myRowResult。