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

时间:2015-08-06 23:05:08

标签: excel-vba vba excel

我有一个工作表,其中A列包含以空格分隔的名字和姓氏。同一工作表中的列L具有首选名称,但仅适用于某些行。我想从第2行滚动到UsedRange,如果列L中存在值,则获取该值并将A列中的First Name替换为该值。

实施例: A栏:托马斯爱迪生 L栏:汤姆

我想将A栏改为Tom Edison。

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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