将重复的行值传递给excel中的数组

时间:2016-09-20 14:48:38

标签: arrays excel vba vlookup

我在Excel中有一个如下表格,

Hub Depend
a   b
a   c
b   d
b   e
b   f
c   g
c   h
d   i
d   j
f   k
h   l
h   m
m   o

我需要将Hubs和Depends提取到像这样的数组

(b,d) and (b,e) and (b,f).

我的代码是:

For i = 2 To lastrow
sid = Cells(i, 1).Value
res = WorksheetFunction.VLookup(sid, Sheet1.Range("A:A"), 2, False)
Next

但是当我使用VLOOKUP时它只给我(b,d)并且在找到第一场比赛后没有处理。

1 个答案:

答案 0 :(得分:0)

嗯,希望这可以帮到你:

Sub SinaNouri()
    Dim i As Range
    Dim rng1 As Range
    Dim c As Integer 'just a counter
    Dim myArray()
    Set rng1 = Range("A2:A14") 'the range of the first column

    c = 0
    For Each i In rng1
        c = c + 1
        ReDim Preserve myArray(1 To c)
        myArray(c) = "(" & i.Value & "," & i.Offset(0, 1).Value & ")"
    Next i
End Sub

请注意

myArray(#)会有文字(Strings)而非数字。如果你想处理数字,请使用:

Sub SinaNouri()
    Dim i As Range
    Dim rng1 As Range
    Dim c As Integer 'just a counter
    Dim myArray()
    Set rng1 = Range("A2:A14") 'the range of the first column

    c = 0
    For Each i In rng1
        c = c + 1
        ReDim Preserve myArray(1 To c)
        myArray(c) = i.Value & "," & i.Offset(0, 1).Value '!!!!!!
    Next i
End Sub

并且myArray(#)以分段方式使用它,这样Split(myArray(2), ",")。您删除逗号,并只获取数字以根据需要使用它。