excel - 根据另一个单元格的开头替换特定的单元格值
问题描述
我有电子表格,其名称在Last, First Name
A 列中列出,然后在 S 列中是分配给该原始个人的人的姓名。我需要在 S 列中搜索两个特定名称,然后根据 A 列中姓氏的开头,将 S 列中的条目更改为不同的名称。
例如,在进行任何更改之前:
- 在 S 列中,如果条目是 Bert,请检查 A 列。
- 如果该值以 AK 开头,则将 Bert 替换为 Grover
如果它以 LZ 开头,则将其替换为 Elmo。
此外,对于 S 列,根据 AK = Elmo 和 LZ = Grover 查找并替换 Ernie。
将 S 列中的其他条目保持原样。
最后,如果 S 列中的值为 Grover,则将 T 列中它旁边的单元格更改为 Example1
- 如果是 Elmo,则将 T 列中旁边的单元格更改为 Example2
- 否则不要更改 T 列中的任何内容
代码运行后的期望结果(添加突出显示只是为了显示更改的内容 - 不是要求):
解决方案
由于您需要更改 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