使用所输入条件的搜索范围将值从一张纸复制到另一张纸

时间:2018-07-27 10:43:24

标签: excel vba excel-vba excel-2010

我正在寻求帮助...以下是我尝试实现的代码和一些图像。我创建了一个选择器,当您输入数量时。我希望它接受包含数量的行,并将其传递到下一个可用行的另一张纸上。我的代码没有产生错误,但也没有任何作用。

我希望输入的行数范围为J:P,然后将其粘贴到D列的下一个空白行中的另一个工作表中,因为A-C中已经包含了条目。这里有人可以帮忙吗?

    Sub Add()

    Dim searchRange As Range
    Dim foundCell As Range
    Dim mysearch As Integer
    Dim iRow As Long
    Dim ws1, ws2 As Worksheet

    Set ws1 = Worksheets("Output")
    Set ws2 = Worksheets("Selector")
    iRow = Sheets("Output").Range("D2").End(xlUp) + 1

    mysearch = Sheets("Selector").Range("N10").Value

    With Sheets("Selector")
        Set searchRange = Sheets("Selector").Range("N12:N35") ', .Range("A" & .Rows.Count).End(xlUp))
    End With

    Set foundCell = searchRange.Find(what:=mysearch, Lookat:=xlWhole, MatchCase:=False, SearchFormat:=False)
    If Not foundCell Is Nothing Then
        ws1.Cells(iRow, 4).Value = foundCell.Offset(0, -4).Value       
'and so on
    End If

    End Sub

这是选择器 enter image description here

在这里我要粘贴值(以不同顺序)。 enter image description here

1 个答案:

答案 0 :(得分:1)

尝试以下操作,我只是对您的代码做了一些修改,并且我认为它应该可以正常工作:

Sub Add()
    Dim foundCell As Range
    Dim mysearch As Integer
    Dim iRow As Long, Last As Long
    Dim ws1 As Worksheet, ws2 As Worksheet

    Set ws1 = Worksheets("Output")
    Set ws2 = Worksheets("Selector")

    iRow = ws1.Cells(ws1.Rows.Count, "D").End(xlUp).Row + 1
    Last = ws2.Cells(ws2.Rows.Count, "N").End(xlUp).Row

    mysearch = ws2.Range("N10").Value

    Set foundCell = ws2.Range("N12:N" & Last).Find(what:=mysearch, Lookat:=xlWhole)
    If Not foundCell Is Nothing Then
        ws1.Cells(iRow, 4).Value = foundCell.Offset(0, -4).Value
    End If

End Sub