搜索范围中的值并将其与另一个范围进行比较。如果存在,请为其指定一个特定值

时间:2016-04-04 11:10:01

标签: excel vba excel-vba excel-formula excel-2010

我有两个范围(都是2维)。 R1(H1:M4)包含R2中单元格的几个可能值的列表(A6:N15)。 R2可能包含空白单元格。如果R2中的单元格与R1中的单元格匹配,我想在匹配的R1值中输出列中的最后一个单元格(N1:N4)。

我在P6(嵌套的Iferror)中使用以下公式:

IF(A6="", "Blank", 
  IFERROR(VLOOKUP(A6, $H$1:$N$4, 7,FALSE), 
    IFERROR(VLOOKUP(A6, $I$1:$N$4, 6,FALSE), 
      IFERROR(VLOOKUP(A6, $J$1:$N$4, 5,FALSE), 
        IFERROR(VLOOKUP(A6, $K$1:$N$4, 4,FALSE), 
          IFERROR(VLOOKUP(A6, $L$1:$N$4, 3,FALSE), 
            IFERROR(VLOOKUP(A6, $M$1:$N$4, 2,FALSE), 
              IFERROR(VLOOKUP(A6, $N$1:$N$4, 1,FALSE), "None"))))))))

请注意,由于Vlookup,我使用的是H1:N4范围。

这给了我一个解决方案,但我想要一个更有效的解决方案。

3 个答案:

答案 0 :(得分:0)

有帮助吗?

Sub Test()
    Dim R1 As Variant, R2 As Variant, x As Variant, y As Variant
    Set R1 = Range("H1:M4")
    Set R2 = Range("A6:N15")
    For Each x In R1
        If x.Value = "" Then
        GoTo skip
         End If

        For Each y In R2
            If y.Value = "" Then
                y.Offset(0, 16) = "Blank"
            ElseIf x = y Then
            y.Offset(0, 16) = x
            End If
        Next y
skip:
Next x
End Sub

答案 1 :(得分:0)

以下作品:

websites <- data.frame(rbind("www.nytimes.com", "www.google.com", "www.facebook.com"))

答案 2 :(得分:0)

you could try this

Option Explicit

Sub FindThem()
Dim rng1 As Range, rng2 As Range, cell As Range
Dim strng As String
Dim i As Long, iRow As Long, nCol As Long

Set rng1 = Range("H1:M4")
Set rng2 = Range("A6:N15")
nCol = rng1.Columns.Count

For i = 1 To rng1.Rows.Count
    strng = strng & Join(Application.Transpose(Application.Transpose(rng1.Rows(i))), "-") & "-"
Next i
strng = "-" & strng ' this is the string that collects all rng1 values

For Each cell In rng2
    i = InStr(strng, "-" & cell.Value & "-")
    If i > 0 Then
        iRow = Len(Left(strng, i + 1)) - Len(Replace(Left(strng, i + 1), "-", "")) ' count the "position" of the value in the string
        cell.Offset(, 16) = rng1(Int(iRow / nCol) + IIf(iRow Mod nCol = 0, 0, 1), 7)
    End If
Next cell
End Sub

which makes much less iterations than looping through both R1 and R2

it would be fine to know which is the fastest, provided speed is an issue you're facing

of course, but that should be an issue for all possible solutions, values in R1 must be unique, otherwise only their first occurrence in R2 (searching row by row and then column by column) would be catched