简体   繁体   中英

Replace part of text in a cell with text from another cell using VBA

I have a worksheet with Column A containing First and Last Name separated by a space. Column L in the same sheet has Preferred First Name but for only some rows. I would like to scroll from row 2 to UsedRange and if a value exists in Column L, then take that value and replace First Name in Column A with that value.

Example: Column A: Thomas Edison Column L: Tom

I would like to change Column A to Tom Edison.

Any help would be highly appreciated.

Sub names()
Dim nick As String
Dim last As String
Dim full As String
Dim midd As Integer
Dim lastRow As Long

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

For i = 2 To lastRow

    If Cells(i, 12).Value <> "" Then
        nick = Cells(i, 12).Value
        midd = InStr(1, Cells(i, 1), " ")
        last = Mid(Cells(i, 1), midd + 1, 99)
        full = nick & " " & last
        Cells(i, 1).Value = full
    End If

Next

End Sub
Option Explicit

Public Sub updateNames()
    Dim ws As Worksheet, n As Range, p As String, ur As Range
    Set ws = Sheet1
    Set ur = ws.Range("A2:A" & ws.Cells(ws.UsedRange.Rows.Count + 1, 1).End(xlUp).Row)
    For Each n In ur
        p = n.Offset(0, 11).Value2
        If Len(p) > 0 Then n.Value2 = p & " " & Split(n.Value2)(1)
    Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM