简体   繁体   English

使用VBA用另一个单元格中的文本替换单元格中的部分文本

[英]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. 我有一个工作表,其中A列包含名和姓,中间用空格分隔。 Column L in the same sheet has Preferred First Name but for only some rows. 同一工作表中的L列具有“首选名字”,但仅适用于某些行。 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. 我想从第2行滚动到UsedRange,如果L列中存在一个值,则采用该值并将A列中的First Name替换为该值。

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

I would like to change Column A to Tom Edison. 我想将A栏更改为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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 VBA:如何从一个单元格复制一部分字符串,并用它替换另一单元格的一部分? - VBA: How to copy part of the string from one cell and replace part of another cell with it? 希望在Powerpoint中查找文本并使用VBA在excel中使用单元格中的文本进行替换,但始终会出错 - Looking to find text in powerpoint and replace using text from a cell in excel using vba, but keep getting error 使用VBA更改Excel单元格中文本字体的一部分 - Change Part of text font in Excel cell using vba 如果找到部分文本单元格,则复制Excel VBA - Copy if part of the text cell found excel VBA 使用VBA选择其中包含文本的单元格 - Using VBA to select a cell with text in it 在Excel VBA中将单元格中的文本与另一个单元格中的“ = text”进行比较 - Comparing text in cell with “=text” in another cell with excel VBA 在一个工作表中查找单元格文本,在另一工作表中查找,然后用vba偏移 - Find cell text from one worksheet, in another sheet, then offset with vba 使用另一个单元格的值动态替换单元格公式的一部分 - Replace part of a cell formula dynamically using value of another cell VBA将单元格值复制到另一个单元格文本字符串中 - VBA to copy cell value into another cell text string 使用VBA在电子邮件的超链接内的单元格中插入文本 - Insert text from cell within Hyperlink in a email using VBA
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM