Excel - 在单元格匹配后,在标题 - V2之间返回值

时间:2012-08-13 14:56:13

标签: excel excel-vba excel-2007 vba

Example

此问题是我之前发布的问题的延续: Excel - Return value, after cell has been matched, between headers

和以前一样(以及更多):

•如果数字为负数:

•使用MATCH检查范围内(标题之间)是否有对应的(正)数字 AND'IDX'相同;

•如果MATCH输出已匹配的F的ID(第1列)的值,则输出已匹配的负值的ID;

•如果没有,不做任何事。

问题是:

•它需要循环,因为负值可以在正值之后;

•标题之间必须包含搜索,且idx必须相同。我认为我上传的图片很清楚,很有希望。

我已经尝试修改lori_m中的上一个答案,添加了一个新的变量和条件,但所有内容都被压缩了:

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

我非常感谢所有的帮助。

1 个答案:

答案 0 :(得分:1)

这里有一些VBA代码,在40,000行上大约需要0.4秒:

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