有条件的复制粘贴

时间:2015-01-20 16:37:52

标签: macros conditional

任何人都可以帮我处理一个执行以下操作的宏。我在表1中有数据,标题和表2只有标题,没有数据。我需要一个宏来搜索工作表1和工作表2的匹配标题,并将粘贴数据复制到工作表2中。例如:如果工作表1和工作表1 2具有标题发票,然后表1中的数据应粘贴到该标题下的表2中。但问题在于数据的粘贴。宏应粘贴每张发票,留下下一张发票中的3行。类似地,它应该对Sheet2中存在的其他标题执行例如:(Sheet1)Invoice Inv Date Amount 251 5/5/14 125150 5656 10/8/14 85000

表(2)帐户GL发票邀请日期DB xxxx 251 5/5/14

3行后DB xxxx 5656 10/8/14

我检查了其他宏,但无法在3行后粘贴数据。请帮帮我。

1 个答案:

答案 0 :(得分:0)

你走了。请注意,您需要将工作表名称分别更改为“Source”和“Target”。

Sub copyPaste()

    Dim srcColumnName As String
    Dim srcColumnIndex As Integer
    Dim srcRowIndex As Integer
    Dim trgtColumnName As String
    Dim trgtColumnIndex As Integer
    Dim trgtRowIndex As Integer
    Dim srcItemColumnIndex As Integer
    Dim trgtItemColumnIndex As Integer
    Dim srcItemName As String

    srcColumnIndex = 1
    srcRowIndex = 1

    Do While (1)

        trgtColumnIndex = 1
        trgtRowIndex = 1

        srcColumnName = Worksheets("Source").Cells(srcColumnIndex, srcRowIndex).Value

        'MsgBox ("Source Column Name: " + srcColumnName)

        If (srcColumnName = "") Then
            Exit Do
        End If

        Do While (1)

            trgtColumnName = Worksheets("Target").Cells(trgtColumnIndex, trgtRowIndex).Value

            'MsgBox ("Target Column Name: " + trgtColumnName)

            If (trgtColumnName = "") Then
                Exit Do
            End If

            srcItemColumnIndex = 2
            trgtItemColumnIndex = 2

            If (trgtColumnName = srcColumnName) Then

                Do While (1)

                    srcItemName = Worksheets("Source").Cells(srcItemColumnIndex, srcRowIndex).Value

                    'MsgBox ("Source Item : " + srcItemName)

                    If (srcItemName = "") Then
                        Exit Do
                    End If

                    Worksheets("Target").Cells(trgtItemColumnIndex, trgtRowIndex).Value = Worksheets("Source").Cells(srcItemColumnIndex, srcRowIndex).Value

                    srcItemColumnIndex = srcItemColumnIndex + 1
                    trgtItemColumnIndex = trgtItemColumnIndex + 3

                Loop

            End If

            trgtRowIndex = trgtRowIndex + 1

        Loop

        srcRowIndex = srcRowIndex + 1

    Loop

    MsgBox ("Program Completed successfully !!! ")

End Sub

此致 Nirmalya