我有点不清楚你想做什么。这是我的解释:假设对于工作表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
我会得到法“范围”对象的_Worksheet失败在这:secondWs .Range(“B”&matchIndex).Value = firstWs.Range(“A”&i).Value - Patrik Frid 14分钟前 –
您可以验证'matchIndex'是否包含值?在'If Not Applicaiton ...'行下,插入:'Debug.Print“mi:”&matchIndex'。当你执行这个宏时,这一行将把值打印到即时窗口(通过按Ctrl + G访问)。 – Vegard