如何在ExcelVBA中将单元格分离并剪切到下一个单元格?

How to seperate and cut cells to the next one in Excel VBA?

我有一个包含 ~230 个字符的单元格(没有 space),我想在单元格中找到“%”符号,然后剪切单元格的其余部分并粘贴到下一个单元格中底部。这样做直到找到所有 %。

Sub test()
Dim c As Range
Range("B12").Select
i = 1
Set c = Selection.Find(What:="%", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
If Not c Is Nothing Then
    Do
    c.Cut c.Offset(i, 0)
    Set c = Selection.Find(What:="%", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
        i = i + 1
    Loop Until c Is Nothing
End If
End Sub

使用 Split 会容易得多。我们可以将整个文本放入一个字符串变量中,然后根据 % 的每次出现将其拆分,然后将数组输出到单元格,跳过空白并重新添加 % 字符。

Sub Example()
    Dim InputRange As Range
    Set InputRange = Range("B12")

    Dim InputText As String
    InputText = InputRange.Value
    
    Dim TextArray() As String
    TextArray = Split(InputText, "%")
    
    Dim i As Long
    For i = 0 To UBound(TextArray)
        If TextArray(i) <> "" Then
            InputRange = TextArray(i) & IIf(i <> UBound(TextArray), "%", "")
            Set InputRange = InputRange.Offset(1, 0)
        End If
    Next
End Sub