在列值的范围的Excel VBA串连列1 2

问题描述:

我有一组行&列如下在列值的范围的Excel VBA串连列1 2

 
Column1 Column2 
123  Value1 
456  Value1 
789  Value2 
101  Value2 
234  Value2 
567  Value3 
890  Value4 

I would like to concatenate column1 based on column2 range like: 

Column3 
123 
123,456 
789 
789,101 
789,101,234 
567 
890 

我尝试这样使用式和干的,但有一种更好的方式(如在宏)来做到这一点?

= IF(B2 = B1,C1 & “” & C2,C2)

并挑选为每个值

+0

是什么样的,你认为的“好”的一个VBA解决方案?该公式似乎很简单,容易,紧凑... – 2011-03-04 20:02:46

井的最后一行,则该宏会做的。不过,我不一定会说这样比较好。

Sub Macro1() 
    Dim Source As Range 
    Dim Control As Range 
    Dim Output As Range 
    Set Source = Range("A1") 
    Set Control = Range("B1") 
    Set Output = Range("C1") 
    Dim StoreHere As String 
    Dim Row As Integer 
    Dim AddItOn As Boolean 

    Row = 1 
    StoreHere = "" 

    While (Not (IsEmpty(Source.Cells(Row, 1)))) 
     If (Row > 1) Then 
      If (Control.Cells(Row, 1) = Control.Cells(Row - 1, 1)) Then 
       AddItOn = True 
      Else 
       AddItOn = False 
      End If 
     Else 
      AddItOn = False 
     End If 

     If (AddItOn = True) Then 
      StoreHere = StoreHere & "," & Source.Cells(Row, 1) 
     Else 
      StoreHere = Source.Cells(Row, 1) 
     End If 

     Output.Cells(Row, 1).NumberFormat = "@" 
     Output.Cells(Row, 1) = StoreHere 
     Row = Row + 1 
    Wend 
End Sub 
+0

哇!它像一个魅力工作,感谢这一点。 – Ara 2011-03-04 14:15:52

这里有一个小选项

Sub Macro1() 
    Dim cl As Range 

    Set cl = [A1] ' set to where your data starts 
    Do While cl <> "" 
     If cl.Cells(1, 2) = cl.Cells(0, 2) Then 
      cl.Cells(1, 3) = cl.Cells(0, 3) & "," & cl 
     Else 
      cl.Cells(1, 3) = CStr(cl) 
     End If 
     Set cl = cl.Cells(2, 1) 
    Loop 
End Sub