VBA:dynamic组合两组列

我有一组列,其间有一些列,然后是另一组列,即:

之前:

ColA ColB ColC ColA ColB ColC RandomCol1 RandomCol2 ColA ColB ColC ColA ColB ColC 1 2 3 4 5 6 N/AN/A 7 8 9 10 11 12 

后:

 ColA ColB ColC RandomCol1 RandomCol2 1;4;7;10 2;5;8;11 3;6;9;12 N/AN/A 

如果第一组是“空白”:

之前:

  ColA ColB ColC ColA ColB ColC RandomCol1 RandomCol2 ColA ColB ColC ColA ColB ColC blank blank blank blank blank blank N/AN/A 7 8 9 10 11 12 

后:

 ColA ColB ColC RandomCol1 RandomCol2 7;10 8;11 9;12 N/AN/A 

我想合并每列的每行中的值与相同的名称分隔; 然后删除剩余的列。 此外,如果第一组中的值是“空白”,那么它应该只取第二组中的值(在随机列之后)

随机列不应该组合

我试过这似乎并不工作时,之间有随机列(也不知道如何添加逻辑跳过第一个“组”如果值是“空白”:

  For DestCol = StartCol To EndCol For ReadCol = DestCol + 1 To EndCol If Cells(1, DestCol) = Cells(1, ReadCol) Then For i = 2 To lastRow If Cells(i, ReadCol) <> "" Then Cells(i, DestCol) = Cells(i, DestCol) & ";" & Cells(i, ReadCol) End If Next i End If Next ReadCol Next DestCol 

处理完毕后,您需要删除重复的列。

注意:你会注意到我缩短了柜台的名字。 对于第一个柜台,我总是使用一个字母的名字,而对于类似的柜台我总是使用一个数字。 例如:如果我使用Cells(x, y)作为外部循环,我将使用Cells(x1, y1)作为下一个内部循环。 我这样做的原因是计数器通常会在代码中重复多次,长的描述性计数器名称会造成混乱。 这实际上使代码难以阅读。

 Sub CombineColumns() Const STARTCOLUMN As Long = 1 Const ENDCOLUMN As Long = 14 Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim lastRow As Long, i As Long, y As Long, y1 As Long lastRow = Range(Columns(STARTCOLUMN), Columns(ENDCOLUMN)).Find(What:="*", After:=Cells(1, STARTCOLUMN), SearchOrder:=xlByRows, SearchDirection:=xlPrevious) For y = STARTCOLUMN To ENDCOLUMN For y1 = y + 1 To ENDCOLUMN If Cells(1, y) <> "" And Cells(1, y) = Cells(1, y1) Then For i = 2 To lastRow If Cells(i, y1) <> "" Then Cells(i, y) = IIf(Cells(i, y) <> "", Cells(i, y) & ";", "") & Cells(i, y1) End If Next i Columns(y1).Delete y1 = y1 - 1 End If Next y1 Next y Application.Calculation = xlCalculationAutomatic Application.ScreenUpdating = True End Sub