Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA - Excel : Split string in a different column

Tags:

split

excel

vba

I want the user of my excel file to enter a sentence in the cell "B2" and then have a Sub to parse the sentence in a different column (from D2 to Dn). So for example, if you type "aaa bbb ccc ddd" in B2, you should have as a result :
D2 : aaa
D3 : bbb
D4 : ccc
D5 : ddd

I found how to split the sentence with VBA using the split function, but I have a hard time populating the column D as I don't know how to define the last row (Dn). Here is what I am using so far :

Sub splitAddress()
Dim strAddress As String

strAddress = Range("B2").Value
Range("D2:D9").Value = WorksheetFunction.Transpose(Split(strAddress, " "))

End Sub

I want to modify the "D2:D9" as D9 isn't always gonna be the last row of the column. How to write that it should populate from D2 to Dn according to the number of words in my B2 cell? Thanks in advance !

like image 790
Phalanx Avatar asked Jan 24 '26 20:01

Phalanx


1 Answers

There are probably more elegant ways to do this, but if you split the address into an array you can get the number of elements in the array using Ubound and use .Resize to increase the number of rows in your range:

Sub splitAddress()
  Dim strAddress As String
  Dim strAddressParts() As String
  Dim numParts As Integer

  strAddress = Range("B2").Value

  strAddressParts = Split(strAddress, " ")
  numParts = UBound(strAddressParts) + 1

  Range("D2").Resize(numParts).Value = WorksheetFunction.Transpose(strAddressParts)
End Sub
like image 160
Glenn Stevens Avatar answered Jan 27 '26 21:01

Glenn Stevens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!