如何根据单元格值

时间:2017-09-08 15:18:33

标签: excel vba excel-vba

我需要代码根据workbook1的{​​{1}}列中的单元格值将workbook2中的一行表格复制到E。如果匹配则需要复制该行,并且需要更改它匹配的单元格,以便不再复制

伪码:

Workbook1

我在Dispatch表上有一个按钮来运行代码,而不是让它自动运行。

我在这里找到的当前代码会删除该行,但我需要它才能保留,因为它有时间在另一张纸上制作,并且在一天结束时全部打印出来。

当前代码:

if workbook1 sheet dispatch range E:E= 13 then copy to workbook WIP sheet1. 
AND change cell in workbook1 sheet dispatch range E:E to "131".

我编写的东西不足以满足我的需求,有人能帮忙吗?

1 个答案:

答案 0 :(得分:0)

你的问题有一些不清楚的元素,但这应该做我认为你想做的事情。您的原始代码有一些冗余循环,我发现使用您之前计算过的LastRow更容易进行单个For循环。但是,您可以非常轻松地将该循环转换为“For Each Cell in Range”。

Sub MoveWaitParts()


'Set variables
Dim i As Integer
Dim DispatchSht As Worksheet
Dim WaitSht As Worksheet
Set DispatchSht = ThisWorkbook.Sheets("Dispatch")
Set WaitSht = ThisWorkbook.Sheets("wait parts")

'Find the last rows in each sheet
lastrow = DispatchSht.Cells(DispatchSht.Rows.Count, "E").End(xlUp).Row
lastrow2 = WaitSht.Cells(WaitSht.Rows.Count, "A").End(xlUp).Row

'Confirm with user
Dim Response As VbMsgBoxResult
Response = MsgBox("Are you sure?", vbYesNo Or vbDefaultButton2)

If Response = vbYes Then
    'Not sure what this is for, but put in by OP
    'This will overwrite the first line if there is only one line on the Wait Parts sheet
    If lastrow2 = 1 Then
        lastrow2 = 0
    End If

    'Loop through each row and see if the cell in column E = 13
    'If it does, copy the entire row and paste it below the next row on the Wait Parts sheet
    For i = 1 To lastrow
    If DispatchSht.Cells(i, "E").Value = "13" Then
        DispatchSht.Rows(i).EntireRow.Copy Destination:=WaitSht.Rows(lastrow2 + 1)
        lastrow2 = lastrow2 + 1

        '************Unclear question elements*********
        '//IF THE ADDED 1 IS SOME SORT OF CODE
        'DispatchSht.Cells(i, "E").Value = DispatchSht.Cells(i, "E").Value & "1"
        '//IF THE ADDED 1 IS AN ARITHMETIC FUNCTION OF SOME SORT
        'DispatchSht.Cells(i, "E").Value = DispatchSht.Cells(i, "E").Value * 10 + 1
        '**********************************************

    End If
    Next i 
End If

End Sub