Split strings in excel (vba)

后端 未结 2 381
予麋鹿
予麋鹿 2020-12-21 07:19

I am currently using this code(from a fellow user here) to find every cell in column b1 and to find the ones that contain a \";\" something like \"hello;goodbye\". The code

相关标签:
2条回答
  • 2020-12-21 07:35

    I found an answer over at

    http://www.excelforum.com/excel-programming/802602-vba-macro-to-split-cells-at-every.html

    This is the solution I was given:

    Sub tgr()
    
    Dim rindex As Long
    Dim saItem() As String
    
    For rindex = Cells(Rows.Count, "B").End(xlUp).Row To 1 Step -1
        If InStr(Cells(rindex, "B").Value, ";") > 0 Then
            saItem = Split(Cells(rindex, "B").Value, ";")
            Rows(rindex + 1 & ":" & rindex + UBound(saItem)).Insert
            Cells(rindex, "B").Resize(UBound(saItem) + 1).Value =     WorksheetFunction.Transpose(saItem)
        End If
    Next rindex
    
    End Sub
    
    0 讨论(0)
  • 2020-12-21 07:55

    I know it's close to what you have, but I wanted to suggest you use Application.ScreenUpdating. This will save considerable time, especially when inserting/deleting rows in Excel. I also wanted to suggest you change the variable names to somehting a little more meaningful.

    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
    

    P.S. Smaller alterations is to use "2" instad of "B". If you are using cells() instead of Range(), may as well go all the way :)

    0 讨论(0)
提交回复
热议问题