我有一组列,其中有一些列,然后是另一组列,即:
在此之前:
ColA ColB ColC ColA ColB ColC RandomCol1 RandomCol2 ColA ColB ColC ColA ColB ColC
1 2 3 4 5 6 N/A N/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/A N/A
如果第一组为“空白”:
在此之前:
ColA ColB ColC ColA ColB ColC RandomCol1 RandomCol2 ColA ColB ColC ColA ColB ColC
blank blank blank blank blank blank N/A N/A 7 8 9 10 11 12
之后:
ColA ColB ColC RandomCol1 RandomCol2
7;10 8;11 9;12 N/A N/A
我希望将每一列的每一行中的值用;
分隔的相同名称组合起来,然后删除剩馀的列。此外,如果第一组中的值是“空”的,那么它应该只接受第二组的值(在随机列之后)。
不应组合随机列。
我尝试过这样做,当中间有随机列时,这种方法似乎不起作用(如果值为“空”,也不知道如何添加跳过第一个"group“的逻辑:
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
发布于 2016-12-04 22:19:42
处理完重复列后,需要删除它们。
注意:,您会注意到我缩短了计数器的名称。我总是使用一个字母名称的第一个柜台和一个字母与数字类似的柜台。例如:如果对外部循环使用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
https://stackoverflow.com/questions/40959204
复制相似问题