有没有更好的方法来搜索带有列的列并将偏移量复制到另一张纸上?

时间:2019-04-25 11:59:04

标签: excel vba

我希望使用X列Sheet1.values搜索Y列Sheet2 找到匹配项后,Sheet2(z)下一列的值将复制到Sheet 1的Y列

如您所见,我并不是最擅长编码的人。

标准excel。

  Sub searchingit()

  Dim rowNum As Integer
  Dim countOf As Integer
  DO
  DoEvents
  rowNum = rowNum + 1
  dudetoFind = Sheets("Sheet1").Range("X" & rowNum).Value
  wheretoFind = Sheets("Sheet2").Range("Y:Y").Value

  If dudetoFind.Value = wheretoFind.Value Then

  wheretoFind.Offset(0, 1).Copy
  wheretoFind = Sheets("Sheet1").Range("Y" + rowNum)
  countOf = countOf + 1
  End If

  Loop Until countOf = 2911


  End Sub

比较两列。找到匹配项后,将下一列的偏移值复制到原始工作表中,复制到空X列。

1 个答案:

答案 0 :(得分:0)

VBA代码:

Option Explicit

Sub test()

    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim position As Range, cell As Range, rng1 As Range, rng2 As Range
    Dim LastRow1 As Long, Lastrow2 As Long

    With ThisWorkbook

        Set ws1 = .Worksheets("Sheet1")
        Set ws2 = .Worksheets("Sheet2")

    End With

    LastRow1 = ws1.Cells(ws1.Rows.Count, "X").End(xlUp).Row
    Lastrow2 = ws2.Cells(ws2.Rows.Count, "Y").End(xlUp).Row

    Set rng1 = ws1.Range(ws1.Cells(1, 24), ws1.Cells(LastRow1, 24))
    Set rng2 = ws2.Range(ws2.Cells(1, 25), ws2.Cells(Lastrow2, 25))

    For Each cell In rng1

        Set position = rng2.Find(cell, LookIn:=xlValues, lookat:=xlWhole)

        If position Is Nothing Then
            Debug.Print "Name was not found."
        Else
            ws1.Range("Y" & cell.Row).Value = ws2.Range("Z" & position.Row).Value
        End If

    Next cell

End Sub