VBA: Extract last name

FryGirl

Well-known Member
Joined
Nov 11, 2008
Messages
1,364
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
mI have a column of names but only want to retain the first name. I've tried using this evaluate in VBA, but it keeps giving me a #VALUE!.

VBA Code:
Sub RemoveName()
  With Range("J2", Cells(Rows.Count, "J").End(xlUp))
    .Value = Evaluate(Replace("IF(ISERROR(FIND("","",@)),@,MID(@,FIND("","",@)+2,LEN(@))", "@", .Address))
  End With
End Sub

Contacts Outlook.csv
J
26Peter
27Shepherd, Alan
Contacts Outlook


This is a small sample and in the cell I just want to be left with the first name.
Peter
Alan

Also, as an alternative, how could I do this on just a single cell with a double click?
 

Excel Facts

Using Function Arguments with nested formulas
If writing INDEX in Func. Arguments, type MATCH(. Use the mouse to click inside MATCH in the formula bar. Dialog switches to MATCH.
You're missing a closing bracket at the end of your formula.
 
Upvote 0
That's Perfect Rory. Glad your eyes are younger than mine. Any thoughts on the double click?
 
Upvote 0
Lots of ways - here's one:

VBA Code:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
   Cancel = True
  With Target
    Dim v
    v = Split("," & .Value, ",")
    .Value = Trim$(v(UBound(v)))
  End With
End Sub
 
Upvote 0
Solution
Thanks Rory. I came up with this and it seems to work as well.

VBA Code:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Cancel = True
    If Target.CountLarge > 1 Then Exit Sub
    If Target.Column <> 10 Then Exit Sub
    Dim x As Long: x = InStr(1, Cells(Target.Row, 10), ",") + 2
    Cells(Target.Row, 10).Value2 = Mid(Cells(Target.Row, 10), x, 100)
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,465
Messages
6,124,977
Members
449,200
Latest member
Jamil ahmed

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top