I would like to split my string in Excel between the address and postcode. I want to keep the postcode separately.
By selecting the option - Data -Text to column - delimited - comma-separated - the whole string is divided by 4 pieces, as 3 commas occur.
1 - 21 Willow Court, 1192 Christchurch Road, Bournemouth, BH7 6EG
I found, that it can be done in VBA Excel.
There are a few approaches below:
Excel VBA- remove part of the string
https://www.thespreadsheetguru.com/the-code-vault/2014/2/28/remove-last-character-from-string
How to delete last character in a string with VBA?
How to i remove a text after '*' or '-' character using VBA in excel?
I prepared the VBA code like below:
Sub Textremove()
Dim c As Variant
For Each c In Range("D1:D100")
c.Value = Left(c.Value, InStr(c.Value, ",") - 1)
Next c
End Sub
I am receiving only:
1 - 21 Willow Court
and the error Invalid procedure call or argument, debugging the following line:
c.Value = Left(c.Value, InStr(c.Value, ",") - 1)
So the breakdown occurs after the first comma instead of the last one.
I found an answer regarding this error:
invalid procedure call or argument left
And when my code looks like this:
Sub Textremove()
Dim c As Variant
For Each c In Range("D1:D100")
If InStr(c.Value, ",") > 0 Then
c.Value = Left(c.Value, InStr(c.Value, ",") - 1)
End If
Next c
End Sub
Then error doesn't occur anymore, but I am still getting the stuff until the first comma instead of the last one.
When I change the code a bit:
Sub Textremove()
Dim c As Variant
For Each c In Range("D1:D100")
If InStr(c.Value, ",") > 0 Then
c.Value = Right(c.Value, InStr(c.Value, ","))
End If
Next c
End Sub
I am getting 2 sentences from the right
Bournemouth, BH7 6EG
which are not fixed and change depending on the total length of the string.
How can I receive the string till the last comma instead of the first one? How can I split the whole string between the address and postcode separately?
A good example is here:
https://trumpexcel.com/vba-split-function/
Sub CommaSeparator()
Dim TextStrng As String
Dim Result() As String
Dim DisplayText As String
Dim i As Long
TextStrng = Sheets("Final").Range("D1")
Result = Split(TextStrng, ",", 1)
For i = LBound(Result()) To UBound(Result())
DisplayText = DisplayText & Result(i) & vbNewLine
Next i
MsgBox DisplayText
End Sub
It admittedly splits the whole address, but it is counted still from the first comma.