1

我试图从 sheet1 中找到一个值sheet2(A1:DF5000)。问题是该值可以在 sheet2 中的任何位置。一旦找到匹配项,还有一件事;可以说sheet2 X495我需要它来返回sheet2 X1.

  1. 始终从搜索匹配中返回列
  2. 始终返回第 1 行
  3. 始终使用精确匹配

因此,如果我正在搜索“ABC”并且在sheet2!D14. 它会返回值Sheet2!D1

实际应用:

我正在使用 excel 来跟踪我用于产品的所有 sku。每个站点都需要一个唯一的 sku。所以我有数百个 sku 都是相同的产品。所以我在excel中有一个主列表,第1行作为我的产品然后每一列都有用于每个产品的所有sku

下面的代码可以正常工作,但发生了一些有趣的事情。原来它不是在寻找完全匹配,但它很接近。

谁能帮我搞定这个工作?

如果我不清楚,也随时问我任何问题。

Function GetPart(text As Variant, rCells As Range)
  Dim txt As String
  Dim rRange As Range
  Dim SubjCell

  For Each rRange In rCells
    SubjCell = rRange
    txt = text

    If InStr(txt, SubjCell) <> 0 Then
      GetPart = SubjCell
      Exit For
    Else
      GetPart = "Not Found"
    End If
  Next rRange

End Function
4

1 回答 1

0

这是你正在尝试的吗?我已经对代码进行了注释,以便您理解它不会有任何问题:) 如果您这样做了,请告诉我。

Option Explicit

Function GetPart(rng As Range, rngDB As Range) As Variant
    Dim aCell As Range, strSearch as String

    GetPart = 0

    On Error GoTo Whoa:

    '~~> This is the value which we will search
    strSearch = rng.Value

    '~~> Notice the use of LookAt:=xlWhole. This is to ensure that we
    '~~> do not get False Positives. Using INSTR will give you False
    '~~> Positives. For example searching for "Coke" in "DigitalCoke"
    Set aCell = rngDB.Find(What:=strSearch, LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    '~~> If the match is found
    If Not aCell Is Nothing Then
        '~~> Get value from the first row
        GetPart = aCell.Offset(-(aCell.Row - 1))
    End If

    Exit Function

Whoa:
End Function
于 2013-05-09T05:22:42.433 回答