簡體   English   中英

使用VBA用另一個單元格中的文本替換單元格中的部分文本

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

我有一個工作表,其中A列包含名和姓,中間用空格分隔。 同一工作表中的L列具有“首選名字”,但僅適用於某些行。 我想從第2行滾動到UsedRange,如果L列中存在一個值,則采用該值並將A列中的First Name替換為該值。

示例:A列:Thomas Edison L列:Tom

我想將A欄更改為Tom Edison。

任何幫助將不勝感激。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM