检查列中是否存在值,如果是,则覆盖,如果没有,则在最后一个后面添加新行

问题描述 投票:0回答:1

我对VBA编码还比较陌生,希望对您有所帮助和指导。

我正在尝试比较两个不同工作表(源和目标)上“ A”列中的值,如果值匹配,则覆盖目标中的整个行,如果不存在值,那么我想使用宏在目标工作表的最后一行之后添加新行,并在源工作表中添加数据行,对应于未找到的单元格。该代码可以很好地覆盖该行,但是我真的很想添加新行。我尝试将Else放入循环中,并添加了新行,但是当我再次运行宏时,它将在最后一行之后再次添加同一行,而不是覆盖。我究竟做错了什么?

代码:

    Dim source, desination As Worksheet
    Dim lastrow, lastrow2 As Long
    Set source = Sheets("Sheet2")
    Set destination = Sheets("Sheet1")
    lastrow = source.Cells(Rows.Count, 1).End(xlUp).Row
    lastrow2 = destination.Cells(Rows.Count, 1).End(xlUp).Row
     For j = 2 To lastrow
        For i = 2 To lastrow2
          If Trim(source.Cells(j, 1).Value2) = vbNullString Then Exit For
          If destination.Cells(i, 1).Value = source.Cells(j, 1).Value Then
             destination.Range("A" & i, "O" & i).Value = source.Range("A" & j, "O" & j).Value
          Else
             destination.Range("A" & lastrow2 + 1, "O" & lastrow2 + 1).Value = source.Range("A" &  j,"O" & j).Value
          End If
        Next
     Next
excel vba
1个回答
0
投票

在循环前定义新变量Dim newRow as long并将其设置为newRow = lastrow2 +1然后类似的事情应该在else分支中起作用

   destination.Range("A" & newRow , "O" & newRow).Value = source.Range("A" &  j,"O" & j).Value
   newRow = newRow +1 

[newRow应该跟踪脚本编写的最后一行。

© www.soinside.com 2019 - 2024. All rights reserved.