separate two strings

  • Thread starter Thread starter Max Bialystock
  • Start date Start date
M

Max Bialystock

A cell contains an author's name and a book title separated by a colon.



Charles Dickens : Great Expectations



I need to get "Charles Dickens" into sAuthor

and "Great Expectations" into sTitle.



In this case there is always a space before and after the colon.
 
Perhaps this will help some:

Sub test()
Dim lngTemp As Long
Dim sAuthor As String
Dim sTitle As String

strLiterature = Range("A1").Value
lngTemp = InStr(1, strLiterature, ":", vbTextCompare)
If lngTemp > 0 Then
sAuthor = Trim$(Left$(strLiterature, lngTemp - 1))
sTitle = Trim$(Mid$(strLiterature, lngTemp + 1, Len(strLiterature)))
End If

End Sub
 
one way, assuming data is in column A on sheet1 and you want the data in columns
C & D
Sub split_names()
Dim ws As Worksheet
Dim sName As Variant
Dim i As Long
Dim lastrow As Long
Dim sAuthor As Long, sTitle As Long
sAuthor = 3 ' column C
sTitle = 4 ' column D
Set ws = Worksheets("sheet1")
lastrow = ws.Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To lastrow
sName = Split(ws.Range("A" & i), ":")
ws.Cells(i, sAuthor).Value = sName(0)
ws.Cells(i, sTitle).Value = sName(1)
Next

End Sub
 
and if you wanted to trim the spaces
Option Explicit

Sub split_names()
Dim ws As Worksheet
Dim sName As Variant
Dim i As Long
Dim lastrow As Long
Dim sAuthor As Long, sTitle As Long
sAuthor = 3 ' column C
sTitle = 4 ' column D
Set ws = Worksheets("sheet1")
lastrow = ws.Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To lastrow
sName = Split(ws.Range("A" & i), ":")
ws.Cells(i, sAuthor).Value = Trim(sName(0))
ws.Cells(i, sTitle).Value = Trim(sName(1))
Next

End Sub
 
A cell contains an author's name and a book title separated by a colon.
Charles Dickens : Great Expectations

I need to get "Charles Dickens" into sAuthor

and "Great Expectations" into sTitle.

In this case there is always a space before and after the colon.

CellValue = "Charles Dickens : Great Expectations"
sAuthor = Split(CellValue, " : ")(0)
sTitle = Split(CellValue, " : ")(1)

Rick
 
initial = cells("A1")
mid_index = Instr(intitial, " : ")
name = left(intial,mid_index-1)
title = mid(initial,mid_index+3)
 
Gary,

Thanks for your help.

Max

Gary Keramidas said:
and if you wanted to trim the spaces
Option Explicit

Sub split_names()
Dim ws As Worksheet
Dim sName As Variant
Dim i As Long
Dim lastrow As Long
Dim sAuthor As Long, sTitle As Long
sAuthor = 3 ' column C
sTitle = 4 ' column D
Set ws = Worksheets("sheet1")
lastrow = ws.Cells(Rows.Count, "A").End(xlUp).Row
For i = 1 To lastrow
sName = Split(ws.Range("A" & i), ":")
ws.Cells(i, sAuthor).Value = Trim(sName(0))
ws.Cells(i, sTitle).Value = Trim(sName(1))
Next

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top