Excel - Return value, after cell has been matched,

2019-09-06 18:05发布

Example

This Question is a continuation to the one I posted before at: Excel - Return value, after cell has been matched, between headers

As before (and more):

• If a number is negative:

• Use MATCH to check if there is a correspondent (positive) number in the range (between headers) AND 'IDX' is the same;

• If there is a MATCH output the value of the ID (1st column) of the F that has been matched, and then, output the ID of the negative value that has been matched ;

• If not, do nothing.

The problems are:

• It needs to loop, because the negative value can come after the positive one;

• The search must be contained between headers AND the idx must be the same. I think the image I uploaded is clear, hopefuly.

I've tried modifying the previous answer from lori_m, adding a new variable and condition but everything just went caput:

Names.Add "i", "=$A$1:$A$12": _
Names.Add "v", "=$B$1:$B$12": _
Names.Add "m", "=$D$1:$D$12": _
Names.Add "h", [IF({1},LOOKUP(ROW(i),ROW(i)/(v=INDEX(v,1))))]: _
Names.Add "l", [IF({1},LOOKUP(ROW(i),ROW(i)/(v=INDEX(v,1)),FREQUENCY(-ROW(i),IF(v=INDEX(v,1),-ROW(i),0))-1))]: _
[m]=[IF(COUNTIF(OFFSET(v,h,,l),"=-"&v),CONCATENATE("=",ADDRESS(ROW(i),COLUMN(i),4),"&"" AND ""&INDEX(",ADDRESS(h+1,COLUMN(i)),":",ADDRESS(h+l,COLUMN(i)),",MATCH(-",ADDRESS(ROW(v),COLUMN(v),4),",",ADDRESS(h+1,COLUMN(v)),":",ADDRESS(h+l,COLUMN(v)),",0))"),"")]: _
Names("h").Delete: _
Names("l").Delete

I am very appreciated for all the help.

1条回答
The star\"
2楼-- · 2019-09-06 18:22

Here's some VBA code for this, it takes around 0.4s on 40,000 rows:

Public Sub MatchVals()

    Dim Arr As Variant, dic As Object, v As Variant, Match() As String
    Dim i As Long, j As Long, k As Long, n As Long

    Arr = ActiveSheet.UsedRange.Value2
    Set dic = CreateObject("scripting.dictionary")
    n = UBound(Arr)

    ReDim Match(1 To n, 1 To 1) As String
    k = n
    For i = n To 1 Step -1
        If Arr(i, 3) <> Arr(1, 3) Then
            dic.Add Arr(i, 3) & "|" & Arr(i, 2), i
        Else
            For j = i + 1 To k
                If Arr(j, 3) < 0 Then
                    v = dic(-Arr(j, 3) & "|" & Arr(j, 2))
                    If Not IsEmpty(v) Then
                        Match(v, 1) = Arr(v, 1) & " AND " & Arr(j, 1)
                    End If
                End If
                k = i - 1
            Next j
            dic.RemoveAll
        End If
    Next i

    With ActiveSheet.UsedRange
        .Offset(0, .Columns.Count).Resize(, 1).Value2 = Match
    End With
End Sub
查看更多
登录 后发表回答