如果找不到则搜索并插入

时间:2015-08-10 17:28:54

标签: excel vba copy find

我尝试在两个工作表之间复制一行时遇到了一些障碍。我们可以将第一个工作表视为源,将另一个工作表视为目标。如果APN字段(字符串)在源中但不在目标中,我们需要将整行复制到目标。在目标中存在APN时,仅复制第3列。后者工作正常,但我无法复制整行。 APN字段位于A列,从A2行开始。任何帮助将非常感谢。代码如下:

  Dim targetSheet As Worksheet
  Set targetSheet = targetWorkbook.Worksheets(1)
  Dim sourceSheet As Worksheet
  Set sourceSheet = customerWorkbook.Worksheets(1)
  Dim r As Range
  Dim matched As Range
  sourceNumRows = sourceSheet.Range("A2", Range("A2").End(xlDown)).Rows.Count
  targetNumRows = targetSheet.Range("A2").CurrentRegion.Rows.Count
  Set r = targetSheet.Range("A:A")
  sourceSheet.Range("A2").Select
  Do Until IsEmpty(ActiveCell)
     ' Check for the APN
     APN = ActiveCell.Value
     Set matched = r.Find(APN)
     If matched Is Nothing Then
            'Insert row below at end of target worksheet
            '===================problem area===========
            'At this point I have a field in the source document that does
            ' not have an APN in the destination or target worksheet and 
            'so I need to insert the Active Row to the last row 
            'destination sheet
             '
         targetSheet.Cells(targetNumRows, 0).EntireRow.Insert = ActiveCell.EntireRow.Select
      '======= end of problem area============
     Else
            matched.Offset(0, 2) = ActiveCell.Offset(0, 2)
     End If
     ActiveCell.Offset(1, 0).Select
  Loop

1 个答案:

答案 0 :(得分:0)

您需要分两步执行此操作:插入然后复制行值。您的Cells()引用也出现错误。您正在为该列传递0,该列无效。

改变这个:

targetSheet.Cells(targetNumRows, 0).EntireRow.Insert = ActiveCell.EntireRow.Select

要:

targetSheet.Cells(targetNumRows, 1).EntireRow.Insert
ActiveCell.EntireRow.Copy targetSheet.Cells(targetNumRows, 1)

请注意,编写此文件的方式,它将继续在目标工作表的初始底部插入行。不确定这是否适合你。例如,如果添加三个新行,它将如下所示:

╔════════════╗
║ TargetData ║
╠════════════╣
║ OldData    ║
║ OldData    ║
║ NewRow3    ║
║ NewRow2    ║
║ NewRow1    ║
╚════════════╝
相关问题