替换特定位置的单元格值

Replace cell value in specific location

我有一个包含 3 列数据的工作簿。如果 col A 中的单元格在 col E 中找到它们的匹配值,那么来自 col E 的值将是替换为 col B.

中的值

下面的代码给出了以下结果:

但是我想实现这个:

问题是,如何让 col A 中的每个单元格循环遍历 col E 中的每个单元格并替换 [= =28=]col B 在正确的位置?提前谢谢你

Sub CopyCells1()

Dim i As Integer
Dim Lastrow As Long

Dim rng As Range
Set ws = Workbooks("Control.xlsm").Worksheets("Sheet1")
Set rng = ws.Range("E1:E1" & Lastrow)

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


For i = 1 To Lastrow
    If Cells(i, 1).Value = Cells(i, 5).Value Then
        Cells(i, 5).Value = Cells(i, 2).Value
        Debug.Print Cells(i, 1).Value
    End If
Next
End Sub

您需要通过嵌套循环来处理这个问题,因为对于 E 列中的每个值,您需要在 A 列中找到相应的匹配项,然后将 B 列的值设置回 E 列。

For i = 1 To 8
  For n = 1 To 8
    If Trim(ThisWorkbook.ActiveSheet.Cells(i, 5).Value) = Trim(ThisWorkbook.ActiveSheet.Cells(n, 1).Value) Then
        ThisWorkbook.ActiveSheet.Cells(i, 5).Value = Trim(ThisWorkbook.ActiveSheet.Cells(n, 2).Value)
    End If
  Next n
Next i

没有第二个循环的数组选择

通过Application.Match()比较两个数组,可以一次性得到所有对应的行号。如果发现,B 列的客户端 ID 将输入到 E 列数组中并写回目标;忽略未发现的结果(返回错误),从而保留原始值。

Sub MatchThem()
With Sheet1       ' << change to needed sheet Code(Name)
    Dim lastRow As Long
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    'assign column data to variant arrays
    Dim a: a = .Range("A1:A" & lastRow)
    Dim e: e = .Range("E1:E" & lastRow)
    'match all elements in column E against column A
    Dim RowNums
    RowNums = Application.Match(e, a, 0)
    'assign results based on A-correspondencies to e array
    Dim i As Long
    For i = 1 To UBound(RowNums)
        If IsNumeric(RowNums(i, 1)) Then          ' check for valid row number
            e(i, 1) = .Range("B" & RowNums(i, 1)) ' remember client
        End If
    Next
    'write results to target
    .Range("E1").Resize(UBound(e), 1) = e
End With
End Sub