Excel VBA根据匹配条件复制不同工作表中的相邻列

时间:2014-08-27 23:40:24

标签: excel vba excel-vba

我有一个宏来检查sheet1,如果A列中的值与sheet2中同一列中的值匹配,如果是,则将每个匹配值的相邻单元格从sheet1复制到sheet2。下面是我到目前为止,但我一直在lastrowadd线上得到'运行时错误9',我不知道为什么。任何帮助将不胜感激:)

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

1 个答案:

答案 0 :(得分: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

此外,这不是检查两个匹配的同一列。它会针对Sheet2中的每一列检查Sheet1的每一列。我认为以下代码就是你要找的。

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