2014-08-27 65 views
0

如果列A中的值與工作表2中同一列中的值匹配,那麼我有一個宏來檢查工作表1,如果是,它將爲每個將sheet1中的值匹配到sheet2中。下面是我到目前爲止,但我不斷收到lastrowadd線'運行時錯誤9',我不知道爲什麼。任何幫助,將不勝感激:)Excel VBA根據匹配標準在不同工作表中複製相鄰列

Sub CopyAdjacent() 
    Dim i As Long, j As Long, colStatus As Long, lastrowAdd As Long, lastrowRemove As Long 

    colStatus = 2 'your status column number 
    lastrowAdd = Sheets(「Sheet1」).Cells(Sheets(「Sheet1」).Rows.Count, 1).End(xlUp).Row 
    lastrowRemove = Sheets(「Sheet2」).Cells(Sheets(「Sheet2」).Rows.Count, 1).End(xlUp).Row 

    For i = 1 To lastrowAdd 
     For j = 1 To lastrowRemove 
      If Sheets(「Sheet1」).Cells(i, 1).Value = Sheets(「Sheet2」).Cells(j, 1).Value Then 
       Sheets(「Sheet2」).Cells(j, colStatus).Value = Sheets(「Sheet1」).Cells(i, colStatus).Value 
      End If 
     Next j 
    Next i 
End Sub 
+0

'表(「工作表Sheet」)。將細胞(表(「工作表Sheet」)。Rows.Count,1).END(xlUp).Row'嘗試這種改變爲'表(「工作表Sheet」)。行.Count-1「,看看會發生什麼 – Saechel 2014-08-27 23:46:50

+0

它仍然會給出相同的結果。 – Steven 2014-08-27 23:52:24

回答

0

一對小情侶已經作了修改既包括lastrowAddlastrowRemove已定義的方式。我也從定義中刪除了ij

Sub CopyAdjacent() 
Dim colStatus As Long, lastrowAdd As Integer, lastrowRemove As Integer 

colStatus = 2 
lastrowAdd = Sheets(「Sheet1」).Cells(Rows.Count, 1).End(xlUp).Row 
lastrowRemove = Sheets(「Sheet2」).Cells(Rows.Count, 1).End(xlUp).Row 

For i = 1 To lastrowAdd 
    For j = 1 To lastrowRemove 
     If Sheets(「Sheet1」).Cells(i, 1).Value = Sheets(「Sheet2」).Cells(j, 1).Value Then 
      Sheets(「Sheet2」).Cells(j, colStatus).Value = Sheets(「Sheet1」).Cells(i, colStatus).Value 
     End If 
    Next 
Next 
End Sub 

此外,這不檢查是否在同一列上兩個匹配。它從Sheet1檢查每一列Sheet2與每一列。我認爲下面的代碼是你正在尋找的。

Sub CopyAdjacent() 
' The below line has been changed, you may still omit lastrowRemove 
Dim colStatus, lastrowAdd, lastrowRemove As Integer 

colStatus = 2 
lastrowAdd = Sheets(「Sheet1」).Cells(Rows.Count, 1).End(xlUp).Row 
' The below line is now redundant in the new code 
'lastrowRemove = Sheets(「Sheet2」).Cells(Rows.Count, 1).End(xlUp).Row 

For i = 1 To lastrowAdd 
     If Sheets(「Sheet1」).Cells(i, 1).Value = Sheets(「Sheet2」).Cells(i, 1).Value Then 
      Sheets(「Sheet2」).Cells(i, colStatus).Value = Sheets(「Sheet1」).Cells(i, colStatus).Value 
     End If  
Next 
End Sub 
+0

我在你所做的事情上看到了你的觀點,並且我認爲我已經理解了你的改變,但遺憾的是我還是得到了同樣的錯誤:/ – Steven 2014-08-28 00:29:18

+0

它是否更具體地告訴你錯誤發生的位置。運行時錯誤9用於超出範圍,您的工作表是否明確地稱爲「Sheet1」和「Sheet2」?或者它是否會給您提供額外的內容?還可以嘗試將'colStatus As Long'更改爲'colStatus As Integer'。這可能是因爲我認爲你應該只用整數調用單元格引用,因爲你可以有單元格A1.5 – 2014-08-28 04:59:40

+0

即使將colStatus從Long更改爲Integer,它仍然給出相同行lastrowAdd的相同調試高亮。另外,我的工作表被稱爲Sheet1和Sheet2。 – Steven 2014-08-28 20:54:42