对于 C 列,我需要按长度拆分文本并插入行,如果 C 列中存在空单元格,则将其保留。我还需要根据拆分在 C 列中创建的新单元格为 A 列和 B 列创建空单元格。请参阅下面的“之前”和“之后”图像链接。
Sub test()
Dim txt As String, temp As String, colA As String, colB As String
Dim a, b() As String, n, i As Long
Const myLen As Long = 70
a = Range("a1").CurrentRegion.Value
ReDim b(1 To Rows.Count, 1 To 3)
For i = 1 To UBound(a, 1)
If a(i, 1) <> "" Then
colA = a(i, 1)
colB = a(i, 2)
txt = Trim(a(i, 3))
Do While Len(txt)
If Len(txt) <= myLen Then
temp = txt
Else
temp = Left$(txt, InStrRev(txt, " ", myLen))
End If
If temp = "" Then Exit Do
n = n + 1
b(n, 1) = colA: b(n, 2) = colB
b(n, 3) = Trim(temp)
txt = Trim(Mid$(txt, Len(temp) + 1))
Loop
End If
Next
Range("e1").Resize(n, 3).Value = b
End Sub
我尝试使用 not with "" 和 ReDim。
If a(i, 1) <> "" Then
和 End If
以包含 A 列上的空白单元格。MAX_CNT
表示每行数据拆分后的最大行数。Redim
调整数组大小,则只能更改 last
维度。最初声明一个足够大的数组来处理数据会更容易。Sub test()
Dim txt As String, temp As String, colA As String, colB As String
Dim a, b() As String, n, i As Long
Const myLen As Long = 70
Const MAX_CNT As Long = 10 ' modify as needed
a = Range("a1").CurrentRegion.Value
ReDim b(1 To Rows.Count * MAX_CNT, 1 To 3)
For i = 1 To UBound(a, 1)
' If a(i, 1) <> "" Then ' ** remove
colA = a(i, 1)
colB = a(i, 2)
txt = Trim(a(i, 3))
Do While Len(txt)
If Len(txt) <= myLen Then
temp = txt
Else
temp = Left$(txt, InStrRev(txt, " ", myLen))
End If
If temp = "" Then Exit Do
n = n + 1
b(n, 1) = colA
b(n, 2) = colB
b(n, 3) = Trim(temp)
txt = Trim(Mid$(txt, Len(temp) + 1))
Loop
' End If ' ** remove
Next
Range("e1").Resize(n, 3).Value = b
End Sub