Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Split String Loop

I am trying to split a string and create a loop for going through the cells in the column.There are a few challenges:

  1. Split works for ActiveCell only.

  2. Loop goes through all cells until LastRow but populates all cells with split string values from ActiveCell only.

  3. Split of Array starts with i = 0 even though there is Option Base 1 at the beginning of the Module.

  4. How can I change the location of destination (e.g. instead of splitting string next to existing data, is there an option to manage column numbers)?

Thank you

Option Explicit
Option Base 1

Sub SplitStringLoop()

    Dim txt As String
    Dim i As Integer
    Dim y As Integer
    Dim FullName As Variant
    Dim LastRow As Single

    ReDim FullName(3)

    LastRow = Cells(Rows.Count, "A").End(xlUp).Row

    txt = ActiveCell.Value

    FullName = Split(txt, "-")

    For y = 2 To LastRow

            For i = 1 To UBound(FullName)

                Cells(y, i + 1).Value = FullName(i)

            Next i

   Next y

End Sub
like image 331
LearnForever Avatar asked Jul 28 '14 05:07

LearnForever


People also ask

How do you split a string in VBA?

The VBA Split Function is used is to split a string of text into an array. The text is split based on a given delimiter – e.g. a comma, space, colon etc. You can see that each item separated by the colon sign. We call the colon sign the delimiter.

What does split return in VBA?

If expression is a zero-length string(""), Split returns an empty array, that is, an array with no elements and no data. Optional. String character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter.

How do I convert a string to an array in VBA?

To convert the split string into an array in VBA, we have a function called “SPLIT.” This VBA function. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.


1 Answers

Chris Nelisen outlined the reasons, I had this code written before he posted, so I'll post it anyway.

Option Explicit

Sub SplitStringLoop()

Dim txt As String
Dim i As Integer
Dim y As Integer
Dim FullName As Variant
Dim LastRow As Single

ReDim FullName(3)

LastRow = Cells(Rows.Count, "A").End(xlUp).Row

For y = 2 To LastRow
        Cells(y, 1).Select
        txt = ActiveCell.Value
        FullName = Split(txt, "-")
        For i = 0 To UBound(FullName)
           Cells(y, i + 2).Value = FullName(i)
        Next i
Next
End Sub
like image 143
RowanC Avatar answered Oct 11 '22 13:10

RowanC