2015-10-22 34 views
0

我一直与excel一起工作,但在VBA方面不是很好,所以我需要帮助来制作一个宏,而且我无法获得录制宏工作:(在sheet1和sheet2中搜索相同的值,并将sheet1中的值复制到sheet2

我有一个Excel与2张(工作表Sheet1和Sheet2的)文件。

我想比较从Sheet2的(A列)与工作表Sheet1(列B)文本,如果找到相同的文字在这两张表中,我也希望宏将sheet1中的列A,B,C和D复制到sheet2中的列B,C,D和E上

在表1中,我有超过6000行,不想做这个手动或在Excel中做一个公式,我想要一个宏为我做这个。

床单有标题,有人可以帮我这个吗?

回答

0

我有点不清楚你想做什么。这是我的解释:假设对于工作表1中第X行A列的值 - 如果在Y行第B列的工作表2上找到相应的值 - 您想从工作表1复制行X归属对列ABCD和行Y列粘贴他们在表2 BCD E.

如果这是正确的,试试这个:

Sub copyCells() 
    Dim wb As Workbook, firstWs As Worksheet, secondWs As Worksheet 
    Dim matchIndex As Integer 

    Set wb = ThisWorkbook 
    Set firstWs = wb.Worksheets(1) 
    Set secondWs = wb.Worksheets(2) 

    Application.ScreenUpdating = False 

    ' We'll start at i=2 to account for the header 
    For i = 2 To firstWs.Range("A2:A6000").Rows.count 
     On Error Resume Next 
     ' MATCH will find the row number in sheet 2 - change the range specifications as needed 
     matchIndex = Application.WorksheetFunction.Match(firstWs.Range("A" & i), secondWs.Range("B2:B6000"), 0) 
     Err.Clear 
     On Error GoTo 0 

     ' MATCH will throw an error if it finds no results. 
     ' Hence: if matchindex contains an error, do nothing. 
     ' But if it doesn't contain an error, it must contain a row number - so we can proceed. 
     If Not Application.WorksheetFunction.IsNA(matchIndex) Then 
      secondWs.Range("B" & matchIndex).Value = firstWs.Range("A" & i).Value 
      secondWs.Range("C" & matchIndex).Value = firstWs.Range("B" & i).Value 
      secondWs.Range("D" & matchIndex).Value = firstWs.Range("C" & i).Value 
      secondWs.Range("E" & matchIndex).Value = firstWs.Range("D" & i).Value  
     End If 
    Next i 

    Application.ScreenUpdating = True 
End Sub 
+0

我会得到法“范围”对象的_Worksheet失败在这:secondWs .Range(“B”&matchIndex).Value = firstWs.Range(“A”&i).Value - Patrik Frid 14分钟前 –

+0

您可以验证'matchIndex'是否包含值?在'If Not Applicaiton ...'行下,插入:'Debug.Print“mi:”&matchIndex'。当你执行这个宏时,这一行将把值打印到即时窗口(通过按Ctrl + G访问)。 – Vegard

相关问题