簡體   English   中英

搜索一個范圍內的值,並將其與另一個范圍進行比較。 如果存在,請給它一個特定的值

[英]Search a value in a range and compare it to another range. If it exists, give it a specific value

我有兩個范圍(均為二維)。 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。

這給了我一個解決方案,但是我想要一個更有效的解決方案。

有幫助嗎?

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

以下作品:

Sub FindMatches()
    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
        End If
        For Each y In R2
            If y.Value = "" Then
                y.Offset(0, 16) = "Blank"
            ElseIf x.value = y.value Then
                y.Offset(0, 16) = x.Offset(0, 7 - x.Column)
            End If
        Next y
        End If
    Next x
End Sub

你可以試試這個

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

與循環遍歷R1和R2相比,迭代次數要少得多

如果速度是您面臨的問題,最好知道哪一個是最快的

當然,但是這對於所有可能的解決方案都是一個問題,R1中的值必須唯一,否則僅會捕獲它們在R2中的首次出現(逐行搜索,然后逐列搜索)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM