用于将已找到值的行复制到另一个工作簿表的代码

时间:2013-12-06 06:48:14

标签: vba

我在网上找到了这个代码,用于复制找到值的行并将其粘贴到另一个根据我需要修改的wb的表格中。修改后的2件事对我的更改不起作用 -

  1. 我只需要复制那些与请求匹配的行,例如我的数据在第11行。但变量'last copy row'中的代码会粘贴11之后的所有已用行。
  2. 我修改了原始代码以满足我对2本工作簿的要求。但我在复制代码上遇到运行时错误:

    src.Range(Cells(matchRow, 1), Cells(lastCopyRow, lastCol)).Copy _ tgt.Range("A" & lastPasteRow)

  3. 有人可以指导我出错的地方吗?

    Sub CopyRowAndBelowToTarget()
        Dim wb1 As Workbook
        Dim wb2 as workbook
        Dim src As Worksheet
        Dim tgt As Worksheet
        Dim match As Range
    
        Set wb1= workbooks(srcwb)
        Set wb2 = workbooks (tgtwb)
        Set src = wb1.Sheets("Sheet1")
        Set tgt = wb2.Sheets("Sheet2")
    
        Dim lastCopyRow As Long
        Dim lastPasteRow As Long
        Dim lastCol As Long
        Dim matchRow As Long
        Dim findMe As String
    
        ' specify what we're searching for
        findMe = "s"
    
        ' find our search string in column A (1)
        Set match = src.Columns(1).Find(What:=findMe, After:=src.Cells(1, 1), _
            LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
            SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    
        ' figure out what row our search string is on
        matchRow = match.Row
    
        ' get the last row and column with data so we know how much to copy
        lastCopyRow = src.Range("A" & src.Rows.Count).End(xlUp).Row
        lastCol = src.Cells(1, src.Columns.Count).End(xlToLeft).Column
    
        ' find out where on our target sheet we should paste the results
        lastPasteRow = tgt.Range("A" & src.Rows.Count).End(xlUp).Row
    
        ' use copy/paste syntax that doesn't use the clipboard 
        ' and doesn't select or activate
        src.Range(Cells(matchRow, 1), Cells(lastCopyRow, lastCol)).Copy _
            tgt.Range("A" & lastPasteRow)
    
    End Sub
    

1 个答案:

答案 0 :(得分:0)

这对我有用:

src.Range(src.Cells(matchRow, 1), src.Cells(lastCopyRow, lastCol)).Copy _
        Destination:=tgt.Cells(lastPasteRow + 1, 1)