excel - 在for循环中复制偏移范围

标签 excel vba

我有一个脚本,它循环遍历 ID 号列表,以检查另一个列表中是否有匹配的 ID,如果有匹配的 ID,它将复制相邻列中的电子邮件并将其粘贴到另一个范围中。我在复制偏移范围时遇到问题,因为它似乎没有粘贴任何值。该脚本没有抛出任何错误:

Sub tryThis()

Dim lookHere As Range, pasteHere As Range, cell As Range, searchList As Range

Set List1 = Range(Range("A1"), Range("A1").End(xlDown))
Set List2 = Range(Range("C1"), Range("C1").End(xlDown))
    
For Each cell In List1
    
    Set found = List2.Find(what:=cell, LookIn:=xlValues, LookAt:=xlWhole, MatchCase:=False)

    If Not found Is Nothing Then
        
        cell.Offset(, 1).Resize(, 1).Copy Destination:=Cells(Rows.Count, "G").End(xlUp)
    
    End If
Next cell

End Sub

最佳答案

这个:

cell.Offset(, 1).Resize(, 1).Copy _
      Destination:=Cells(Rows.Count, "G").End(xlUp)

每次运行都会将值复制到同一单元格中,因为End(xlUp)会将您带到列中最后一个占用单元格,而不是第一个空单元格。您需要 Offset() 减一到下一个空位置。也可以通过直接赋值来做到这一点:

Cells(Rows.Count, "G").End(xlUp).Offset(1, 0).Value = cell.Offset(0, 1).Value

编辑:如果您要复制的单元格来自列表 2,则:

Cells(Rows.Count, "G").End(xlUp).Offset(1, 0).Value = found.Offset(0, 1).Value

关于excel - 在for循环中复制偏移范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66294830/

相关文章:

excel - VBA查找N/A错误并将其更改为零

vba - Excel 2013 中使用超出行 65536 的范围时出现问题

vba - 使用 VBA 自动过滤多列,使用来自不同工作表的值

c# - C# 中的 Excel - 2 张纸有问题

C# 等效于 Visual Basic API 调用

excel - 使用 vlookup 公式的列引用

VBA Excel For 循环与变体数组导致 Excel 崩溃

excel - 如何在不为每个行分配按钮的情况下向行添加交互?

php - 导出到 XLS 单元格时如何使 <td> 宽度适合内容

excel - 寻找公式在单个单元格中每个句子的开头添加 "bullet pointers"