【问题标题】:How To Vlookup To Return Multiple Values In One Cell In Excel?如何在Excel中的一个单元格中查找多个值?
【发布时间】:2019-01-22 20:53:32
【问题描述】:

所以我有将多个值粘贴到一个单元格中的代码,但我希望能够在单元格的值之间放置一个分号。

此代码允许 vlookup 查找多个单元格值并将它们输出到一个单元格中。

Function MYVLOOKUP(pValue As String, pWorkRng As Range, pIndex As Long)
'Update 20150310
Dim rng As Range
Dim xResult As String
xResult = ""
For Each rng In pWorkRng
    If rng = pValue Then
        xResult = xResult & ";" & rng.Offset(0, pIndex - 1)
    End If
Next
MYVLOOKUP = xResult
End Function

当我这样做时,它确实会在我想要的值之间放置一个分号,但后面还有十亿个分号。

【问题讨论】:

  • 你能把 Debug.Print rng.Offset(0, pIndex - 1) 放在 xResult = xResult & ";" & rng.Offset(0, pIndex - 1) 之前,看看会返回什么吗?
  • 如果您有 Office 365:=TEXTJOIN(";",TRUE,IF(A1:A1000="MyValue",D1:D1000,"")) 使用 Ctrl-Shift-Enter 作为数组公式
  • @dwirony 它还有一堆 ;之后
  • @scottcraner 我在哪里添加?
  • 这是您在工作表上添加的公式,将范围更改为所需的输入和输出,它不是 vba

标签: excel vba vlookup


【解决方案1】:

我会为此使用一个数组。首先调整其大小以适合整个源:

Dim results As Variant
ReDim results(1 To pWorkRng.Count)

然后为该数组中最后一项的索引维护一个计数器,并在该索引处写入:

Dim currentIndex As Long

For Each rng In pWorkRng
    If Not IsError(rng.Value) Then
        If rng.Value = pValue Then
            currentIndex = currentIndex + 1
            results(currentIndex) = rng.Offset(0, pIndex - 1)
        End If
    End If
Next

当循环完成时,您将获得直到currentIndex 的所有结果,然后是一堆Empty 值;使用ReDim Preserve 截断数组:

ReDim Preserve results(1 To currentIndex)

现在您可以使用String.Join返回一个包含所有结果的字符串:

MYVLOOKUP = String.Join(results, ";")

【讨论】:

    【解决方案2】:

    如果 Mathieu Guindons 方法不起作用,请尝试在以下行之后将以下内容添加到您的代码中:

    xResult = xResult & ";" & rng.Offset(0, pIndex - 1)

        Do While (InStr(xResult, ";;") > 0)
            xResult = Replace(xResult, ";;", ";")
        Loop
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多