我目前正在使用此代码(来自此处的其他用户)来查找 b1 列中的每个单元格并查找包含“;”的单元格比如“你好;再见”。该代码将在“;”处拆分单元格并将“再见”直接放在“你好”下面;在一个全新的行上..
我现在需要的是......如果一个单元格包含多个“;” (即“你好;再见;哟;嗨;嘿”)它将在每个“;”处 split 不仅仅是第一个,然后将每个移动到另一个新行的正下方...
我需要做出哪些改变?
Dim r1 As Range, r2 As Range
Dim saItem() As String
For Each r1 In ActiveSheet.Range("B1", Cells(Application.Rows.Count, 2).End(xlUp))
If InStr(1, r1.Value2, ";") > 0 Then
saItem = Split(r1.Value2, ";")
r1 = Trim$(saItem(0)) & ";"
r1.Offset(1).EntireRow.Insert (xlDown)
r1.Offset(1) = Trim$(saItem(1))
End If
Next r1
最佳答案
我知道它与您所拥有的很接近,但我想建议您使用Application.ScreenUpdating。这将节省大量时间,尤其是在 Excel 中插入/删除行时。我还想建议您将变量名称更改为更有意义的名称。
Sub SplitCells()
Application.ScreenUpdating = False
Dim strings() As String
Dim i As Long
For i = Cells(Rows.Count, 2).End(xlUp).Row To 1 Step -1
If InStr(Cells(i, 2).Value, ";") <> 0 Then
strings = Split(Cells(i, 2).Value, ";")
Rows(i + 1 & ":" & i + UBound(strings)).Insert
Cells(i, 2).Resize(UBound(strings) + 1).Value = _
WorksheetFunction.Transpose(strings)
End If
Next
Application.ScreenUpdating = True
End Sub
附注较小的改变是使用“2”代替“B”。如果您使用 cells() 而不是 Range(),不妨一路走下去:)
关于vba - 在Excel中分割字符串(vba),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8231368/