【问题标题】:Replace cell value in specific location替换特定位置的单元格值
【发布时间】:2021-10-28 16:24:04
【问题描述】:

我有这本包含 3 列数据的工作簿。如果 col A 中的单元格在 col E 中找到匹配值,则 col E 中的值将替换为 col B 中的值

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

但我想实现这个:

问题是,如何让 col A 中的每个单元格循环通过 col E 的每个单元格并替换 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

【问题讨论】:

  • 您需要使用单独的内部 for 循环来步进 Col E 行。
  • @TedroyG 仅供参考 可能对展示Application.Match() 的未记录功能的后期帖子感兴趣。
  • @T.M.我会看看你的帖子。谢谢!

标签: excel vba loops replace copy


【解决方案1】:

您需要通过嵌套循环来处理此问题,因为对于 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

【讨论】:

  • 如果我可以使用 Trim 对此有什么想法吗?如果值有一些空格
  • 非常感谢@jbrekke
【解决方案2】:

没有第二个循环的数组替代

通过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

【讨论】:

    猜你喜欢
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 2020-05-19
    • 2016-01-06
    • 2022-07-29
    • 2021-05-26
    相关资源
    最近更新 更多