我有一个包含40列和~5000行的数据集。在列L和M中,有多行单元格具有换行符,我需要将这些行拆分为单独的行,但是对于这些新行,其他列中的信息保持相同。我已经尝试了多个VBA代码,但似乎没有两个专栏的技巧。
答案 0 :(得分:0)
这适用于数字和字符串,但不适用于公式。它也不适合格式化的单元格:
Sub multilineCellsToSeparateCells(rng As Range)
Dim i As Long, j As Long, ubnd As Long
Dim cll As Range
Dim arrVals As Variant, tempVal As Variant, vItem As Variant
With rng
ReDim arrVals(.Rows(1).Row To rng.Rows.Count, 1 To 1) As Variant
For Each cll In rng.Cells
tempVal = cll.Value2
If InStr(1, tempVal, Chr(10)) > 0 Then
vItem = Split(tempVal, Chr(10))
i = i + 1
ubnd = UBound(vItem)
For j = 0 To ubnd
arrVals(i + j, 1) = vItem(j)
Next j
i = i + ubnd
ElseIf tempVal <> vbNullString Then
i = i + 1
arrVals(i, 1) = tempVal
End If
Next cll
.Value2 = arrVals
.AutoFit ' optional
End With
End Sub
示例强>
在A栏中写下:
A1: 1
A2: 2
A3: 3
A4: This
is
a
test
A5: 5
调用Sub
,输出将为:
A1: 1
A2: 2
A3: 3
A4: This
A5: is
A6: a
A7: test
A8: 5
子修复一次一列。像这样调用它:
Call multilineCellsToSeparateCells(Activesheet.Columns("A"))