在VBA Excel中自动串联

时间:2019-07-09 03:08:17

标签: excel vba

我在excel工作表中列出了在哪些计算机上运行的设备。

示例device Amachine X处运行,BY处运行,另一个device Amachine Z处运行。但是有时候,相同的设备正在多台机器上运行。

是否可以串联显示A devicemachine X,Z上运行?

  

设备|机器

A|X

B|Y

A|Z

我尝试在excel中进行串联。它可以工作,但是列表每小时更新一次,因此我需要记录一个宏。我还必须vlookup放入另一张纸。

我希望它看起来像这样:

  

设备|机器

A |  X,Z

B | Y

1 个答案:

答案 0 :(得分:0)

Sub MakeListCol()


Dim coll As New Collection
Dim c As Range
Dim sPair() As String
Dim sVal As String
Const cSep1 = "|"
Const cSep2 = ","

For Each c In Range("A:A")   ' suppose the "A|X", "B|Y" pairs are in column A
    If IsEmpty(c) Then Exit For ' finish
    sPair = Split(c.Value, cSep1)
    If UBound(sPair) > 0 Then
        On Error Resume Next
        sVal = coll(sPair(0))
        If Err.Number = 0 Then
            On Error GoTo 0
            sVal = sVal & cSep2 & sPair(1)
            coll.Remove (sPair(0))
        Else
            On Error GoTo 0
            sVal = sPair(0) & cSep1 & sPair(1)
        End If
        coll.Add sVal, sPair(0)
    End If
Next

'  here you have a list of all device-machines assignements in coll

Dim i As Long
For i = 1 To coll.Count
    Debug.Print coll.Item(i)
Next

End Sub