如何根据列值复制从 sheet 到 sheet 的范围?

How can I copy range from sheet to sheet based on column value?

我正在尝试将指定范围的单元格从一个 sheet (Sheet2) 复制到另一个 sheet (Sheet1) 中的指定单元格范围) 基于条件。有数百行数据,我想要 VBA 查看每一行的代码,如果满足该行的条件,则将指定的单元格范围从 sheet2 复制到 sheet1。复制的不是整行,而是一行中的四个单元格,还有更多包含数据的单元格。

更具体地说,如果每一行的 AK 列中的值大于 0,我想为每一行复制 B 到 E 列(从第 2 行开始)。我希望此数据是粘贴到 sheet1 中的 B 到 E 列,从第 8 行开始。因此,例如,如果 Sheet 2 中的第 2 行符合条件,我希望 [=18= 中的 B2 到 E2 ] 2 在 sheet 1 中通过 E8 复制到 B8。

我曾尝试改编在 Whosebug 和其他来源的其他问题中找到的代码,但我对 VBA 还很陌生,但没有成功。任何帮助将不胜感激。

Private Sub CopySomeCells()
    Dim SourceSheet As Worksheet
    Dim DestinationSheet As Worksheet
    Dim SourceRow As Long
    Dim DestinationRow As Long

    Set SourceSheet = ActiveWorkbook.Sheets(2)
    Set DestinationSheet = ActiveWorkbook.Sheets(1)

    DestinationRow = 8
    For SourceRow = 2 To SourceSheet.UsedRange.Rows.Count
        If SourceSheet.Range("AK" & SourceRow).Value > 0 Then
            SourceSheet.Range(SourceSheet.Cells(SourceRow, 2), SourceSheet.Cells(SourceRow, 5)).Copy _
                DestinationSheet.Cells(DestinationRow, 2)
            DestinationRow = DestinationRow + 1
        End If
    Next SourceRow
    Application.CutCopyMode = False

    Set SourceSheet = Nothing
    Set DestinationSheet = Nothing
End Sub

如果您只想粘贴值(而不是格式),则按此更改两行:

SourceSheet.Range(SourceSheet.Cells(SourceRow, 2), SourceSheet.Cells(SourceRow, 5)).Copy
DestinationSheet.Cells(DestinationRow, 2).PasteSpecial Paste:=xlPasteValues

或者这样更好(更快且没有剪贴板):

DestinationSheet.Cells(DestinationRow, 2).Resize(1, 4).Value = _
    SourceSheet.Cells(SourceRow, 2).Resize(1, 4).Value