2015-10-12 21 views
0

問題返回找到的值作爲行我有一個樁在片2的數據這是圍繞6K行。 我有一些437我想找到。這些在表1(A欄)中規定。 對於這些我想複製整行並將其放在工作表3中。 工作表1中的值可以在工作表2中多次找到,我需要它們全部。使用值,搜索片2和在片材3

我的解決方案我發現VBA搜索它所有。但它停在437.

Public Sub findfak() 

Dim lastRowS1 As Long 
Dim lastRowS2 As Long 
Dim lastRowS5 As Long 
Dim i As Long 
Dim j As Long 
Dim tempS1 As Long 
Dim temps2 As Long 
Dim tempRow As Long 

lastRowS1 = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row 
lastRowS2 = Sheet2.Cells(Rows.Count, 1).End(xlUp).Row 

Application.ScreenUpdating = False 

    For i = 2 To lastRowS1 
     tempS1 = Sheet1.Cells(i, 1).Value 

     If Not IsError(Application.Match(tempS1, Sheet2.Range("A:A"), 0)) Then 
      lastRowS5 = Sheet5.Cells(Rows.Count, 1).End(xlUp).Row 
      Sheet2.Rows(i).EntireRow.Copy Destination:=Sheet5.Rows(lastRowS5 + 1) 
     End If 

    Next i 

Application.ScreenUpdating = True 
End Sub 
+0

我的猜測是sheet2比sheet1長。您的循環設置爲運行到sheet1 NOT sheet2的最後一行。 – findwindow

+0

如果我更改爲lastRowS2。我在tempS1 = sheet1.cells(i,1).Value上出現錯誤。任何建議? – RickymQrk

+0

因爲你知道sheet2比sheet1長,所以當你用完sheet1中的行時,那個語句將不起作用....你需要兩個循環。 – findwindow

回答

1

試試這個。

Sub findfak() 

Dim lastRowS1 As Long 
Dim lastRowS2 As Long 
Dim lastRowS5 As Long 
Dim i As Long 
Dim j As Long 
Dim tempS1 As Variant 
Dim temps2 As Long 
Dim tempRow As Long 

Dim ws1 As Worksheet 
Dim ws2 As Worksheet 
Dim ws3 As Worksheet 

'change sheets as necessary 
Set ws1 = WorkSheets("Sheet5") 
Set ws2 = WorkSheets("Sheet6") 
Set ws3 = WorkSheets("Sheet2") 

lastRowS1 = ws1.Cells(Rows.Count, 1).End(xlUp).Row 
lastRowS2 = ws2.Cells(Rows.Count, 1).End(xlUp).Row 

Application.ScreenUpdating = False 

For i = 2 To lastRowS1 

    tempS1 = ws1.Cells(i, 1).Value 

    For j = 2 To lastRowS2 

     If ws2.Cells(j, 1) = tempS1 Then 
      lastRowS5 = ws3.Cells(Rows.Count, 1).End(xlUp).Row 
      ws2.Rows(j).EntireRow.Copy Destination:=ws3.Rows(lastRowS5 + 1) 
     End If 

    Next j 

Next i 

Application.ScreenUpdating = True 

End Sub 
+0

謝謝!工作就像一個魅力:) – RickymQrk