首页 > 解决方案 > 根据另一个单元格的开头替换特定的单元格值

问题描述

我有电子表格,其名称在Last, First NameA 列中列出,然后在 S 列中是分配给该原始个人的人的姓名。我需要在 S 列中搜索两个特定名称,然后根据 A 列中姓氏的开头,将 S 列中的条目更改为不同的名称。

例如,在进行任何更改之前:

在此处输入图像描述

代码运行后的期望结果(添加突出显示只是为了显示更改的内容 - 不是要求):

在此处输入图像描述

标签: excelvba

解决方案


由于您需要更改 S 列中的值,因此您需要一个宏来执行此操作。像这样的东西?

Option Explicit
Sub Example()


Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range, cell As Range
Dim str As String
Dim LastRow As Long

Set wb = ThisWorkbook
Set ws = wb.Sheets("Blad1")

LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

Set rng = ws.Range(ws.Cells(1, 1), ws.Cells(LastRow, 1))

For Each cell In rng
    If Asc(Left(cell.Value, 1)) >= 65 And Asc(Left(cell.Value, 1)) < 76 Then
        str = "Grover"
    ElseIf Asc(Left(cell.Value, 1)) >= 76 And Asc(Left(cell.Value, 1)) < 91 Then
        str = "Elmo"
    End If

    If ws.Cells(cell.Row, 19).Value = "Bert" Then
        ws.Cells(cell.Row, 19).Value = str
    End If
    If ws.Cells(cell.Row, 19).Value = "Grover" Then
        ws.Cells(cell.Row, 20).Value = "Example1"
    ElseIf ws.Cells(cell.Row, 19).Value = "Elmo" Then
        ws.Cells(cell.Row, 20).Value = "Example2"
    End If

Next cell


End Sub

推荐阅读