【问题标题】:Is there a better way to search a column with a column and copy the offset to another sheet?有没有更好的方法来搜索一列并将偏移量复制到另一张表?
【发布时间】:2019-04-25 11:59:04
【问题描述】:

我希望用 X 列 Sheet1.values 搜索 Y 列 Sheet2 当找到匹配项时,Sheet2(z) 上下一列的值被复制到 Sheet 1 Column 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。

【问题讨论】:

  • 为什么不用公式:=IF(Sheet1!X:X=Sheet2!Y:Y,Sheet2!Z:Z,"")?实际上,您的代码看起来不会起作用。它会运行吗? • 请附上截图或示例数据以重现它,并查看您的预期结果。

标签: excel vba


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-13
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-08
    相关资源
    最近更新 更多