我有一个宏来检查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
答案 0 :(得分:0)
进行了一些小的更改,包括lastrowAdd
和lastrowRemove
的定义方式。我还从定义中删除了i
和j
。
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
的每一列。我认为以下代码就是你要找的。 p>
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