从另一个工作簿中获取值,并根据列名应用前缀

时间:2018-09-27 15:59:40

标签: excel vba excel-vba

我知道这个问题太简单了。但是,我不知道如何在vba excel中应用我的逻辑。我想将数据从一个工作簿(Book1.xls)或拉到另一工作簿(Book2.xls)。我需要获取Book1的A和B列中的值,并在A列(Book2-详细信息)中为其分配值。然后,对于“已添加”列中的每个值,其前缀应为“ Addition:”,与“已删除”列相同,对于“已删除”列中的每个值,其前缀应为“删除”。可以更改Book1中A列和B列的范围。 enter image description here

谢谢。

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题

Sub AdditionDeletion()

    Dim ws1 As Worksheet
    Set ws1 = Workbooks("Book1").Worksheets("Compare")

    Dim ws2 As Worksheet
    Set ws2 = Workbooks("Book2").Worksheets("Details")

    Dim current As Long
    current = ws2.Range("A" & rows.count).End(xlUp).row + 1

    Dim i As Long
    For i = 3 To ws1.Range("B" & rows.count).End(xlUp).row
        ws2.Range("A" & current) = "Addition:" & ws1.Range("B" & i).Value2
        current = current + 1
    Next i

    For i = 3 To ws1.Range("A" & rows.count).End(xlUp).row
        ws2.Range("A" & current) = "Deletion:" & ws1.Range("A" & i).Value2
        current = current + 1
    Next i

End Sub