尝试使用不同的工作簿进行复制和粘贴,但不会复制正确的值

时间:2017-02-27 17:09:22

标签: excel vba excel-vba

我正在尝试复制并粘贴两个不同的工作簿,但没有复制正确的值。我相信这是因为我在另一个“with”语句中使用“with”语句,但我不知道如何避免这种情况,因为我使用for循环。到目前为止,这是我的代码:

Sub Approval_Flow()
Dim AppFlowWkb As Workbook, ConfigWkb As Workbook
Dim AppFlowWkst As Worksheet, ConfigWkst As Worksheet
Dim aCell As Range
Dim targetRng As Range



Set AppFlowWkb = Workbooks.Open("C:\Users\clara\Documents\Templates and Scripts\Flow Change.xlsx")
Set ConfigWkb = ThisWorkbook
Set AppFlowWkst = AppFlowWkb.Sheets("Editor")
Set ConfigWkst = ConfigWkb.Worksheets("Approval Flows")

With ConfigWkst
    'looking through each column value before moving on to next row
    For Each aCell In .Range("A1:K" & .UsedRange.Rows.Count)
        'if cell is highlighted, copy that row's column D value
        If Not aCell.Interior.Color = RGB(255, 255, 255) Then
            Range("D" & (aCell.row)).Copy
            'in appflow workbook, find empty row in column A and paste
            With AppFlowWkst
                Set targetRng = .Range("A" & Rows.Count).End(xlUp).Offset(1)
                targetRng.PasteSpecial xlPasteValues
            End With

            'Range("C" & (aCell.row)).Copy
            'With AppFlowWkst
                'Set targetRng = .Range("B" & Rows.Count).End(xlUp).Offset(1)
                'targetRng.PasteSpecial xlPasteValues

'once the rows' values have been pasted, move on to next row


        End If
    Next aCell

End With


End Sub

我希望这些评论可以让你很好地理解我想要做什么。此外,一旦我复制并粘贴该行的所有值,我希望For循环不继续该行,而是继续下一行。有关如何实现这一目标的任何建议吗?谢谢!

2 个答案:

答案 0 :(得分:1)

我不认为双重语句是你的问题,但你可以删除第二个:

Set targetRng = AppFlowWkst.Range("A" & Rows.Count).End(xlUp).Offset(1)
targetRng.PasteSpecial xlPasteValues

并查看它是否可以解决您的问题。它至少可以让你消除你的担忧。

事实上,您既不需要声明,也可以执行以下操作:

For Each aCell In ConfigWkst.Range("A1:K" & ConfigWkst.UsedRange.Rows.Count)
    'if cell is highlighted, copy that row's column D value
    If Not aCell.Interior.Color = RGB(255, 255, 255) Then
        ConfigWkst.Range("D" & (aCell.row)).Copy
        'in appflow workbook, find empty row in column A and paste
        Set targetRng = AppFlowWkst.Range("A" & Rows.Count).End(xlUp).Offset(1)
        targetRng.PasteSpecial xlPasteValues
    End If
Next aCell

答案 1 :(得分:1)

您错过了此行.前面的Range,因此它正在从ActiveSheet复制:

Range("D" & (aCell.Row)).Copy

应为.Range("D" & (aCell.Row)).Copy

也就是说,您甚至不需要使用.Copy.Paste,因为您唯一粘贴的是值。只需直接指定它们:

With ConfigWkst
    For Each aCell In .Range("A1:K" & .UsedRange.Rows.Count)
        If Not aCell.Interior.Color = RGB(255, 255, 255) Then
            Set targetRng = .Range("A" & Rows.Count).End(xlUp).Offset(1)
            'Use a direct assignment.
            targetRng.Value = .Range("D" & (aCell.Row)).Value
        End If
    Next aCell
End With