我不会给你看我的代码,因为你会笑。
Stack Overflow 的任何人都不会嘲笑或嘲笑任何 OP 尝试学习和拓展视野的尝试。该网络的存在只是为了鼓励其他开发人员成为最好、最有知识的开发人员,并提出有助于他们实现目标的问题。
为了帮助你的人而展示你的代码总是有帮助的。
要继续您的问题,假设您的单元格始终具有相同数量的分隔符,下面的代码将完全符合您的要求。
Sub SplitContent()
Dim i As Long
Dim c As Long
Dim delim As Long
Dim dCount As Long
Dim endrow As Long
Dim txtArr
endrow = Range("A" & Rows.Count).End(xlUp).Row '<-this gets the last used row in Column A from the bottom up
For i = 2 To endrow '<- initializes loop for rows 2 to endrow
delim = Len(Cells(i, 1)) - Len(Replace(Cells(i, 1), Chr(10), "")) '<-get the number of delimiters in the cell
For dCount = 0 To delim '<- loop for each delimiter
For c = 1 To 4 '<- initializes loop for columns A:D
txtArr = Split(Cells(i, c), Chr(10)) '<-split function that you mentioned
Range("E" & i) = Range("E" & i) & txtArr(dCount) & " " '<- let E = itself + the dCount position of the column
Next c
Range("E" & i) = Range("E" & i) & Chr(10) '<- add carriage return once the column iteration has complete
Next dCount
Range("E" & i) = Left(Range("E" & i), Len(Range("E" & i)) - 1) '<- remove extra carriage return
Next i
End Sub
话虽如此,如果您有不同数量的分隔符,您就会遇到问题。您可能希望采用更动态的路线,并结合一个错误处理程序来处理这些情况,同时快速检查哪个单元格的分隔符数量最多,这样您就不会错过任何数据:
Sub SplitContent()
Dim i As Long
Dim c As Long
Dim delim As Long
Dim dCount As Long
Dim endrow As Long
Dim txtArr
On Error GoTo eHandler '<- this will handle cases where the delimiter count is does not match
endrow = Range("A" & Rows.Count).End(xlUp).Row '<-this gets the last used row in Column A from the bottom up
For i = 2 To endrow '<- initializes loop for rows 2 to endrow
For c = 1 To 4
If Len(Cells(i, c)) - Len(Replace(Cells(i, c), Chr(10), "")) > delim Then
delim = Len(Cells(i, c)) - Len(Replace(Cells(i, c), Chr(10), "")) '<-get the number of delimiters in the cell
End If
Next c
For dCount = 0 To delim '<- loop for each delimiter
For c = 1 To 4 '<- initializes loop for columns A:D
txtArr = Split(Cells(i, c), Chr(10)) '<-split function that you mentioned
Range("E" & i) = Range("E" & i) & txtArr(dCount) & " " '<- let E = itself + the dCount position of the column
Next c
Range("E" & i) = Range("E" & i) & Chr(10) '<- add carriage return once the column iteration has complete
Next dCount
Range("E" & i) = Left(Range("E" & i), Len(Range("E" & i)) - 1) '<- remove extra carriage return
delim = 0
Next i
Exit Sub
eHandler:
If Err.Number = 9 Then
Resume Next
End If
MsgBox Err.Number & vbCrLf & Err.Description
End Sub