excel 复制最后3行,不包括“C”列中有“0”的行

14ifxucb  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(150)

我有个问题。
我想找到另一个文件和工作表中的最后一行,并从A-AD复制最后3行,但"C"列中有"0"的行除外。我想复制的行数始终为3。下面的代码有问题,因为它总是最后只复制一行。

Sub AB ()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

Dim ws As Worksheet
    Dim lastRow As Long, i As Long
    Dim numCopied As Long
    Dim baseWB As Workbook, baseWS As Worksheet
    Dim spWB As Workbook, spWS As Worksheet

    Set baseWB = ThisWorkbook
    Set baseWS = ActiveSheet

    lastRow = spWS.Cells(spWS.Rows.Count, "D").End(xlUp).Row

    numCopied = 0
    For i = lastRow To lastRow - 8 Step -1
        ' Sprawdź, czy w kolumnie C jest 0
        If spWS.Cells(i, "C").Value <> 0 Then
            spWS.Range(spWS.Cells(i, "A"), spWS.Cells(i, "AD")).Copy
            numCopied = numCopied + 1
        End If
        If numCopied = 3 Then
            Exit For
        End If
    Next i

    baseWB.Sheets("Sheet1").Range("E5").PasteSpecial xlPasteValues
    spWB.Close SaveChanges:=False
   
 
   
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub
sqougxex

sqougxex1#

循环内的副本覆盖了前一个副本。除非使用并集,否则它们不是相加的。

Option Explicit
Sub AB()

    Dim spWB As Workbook, spWS As Worksheet
    Dim baseWB As Workbook, baseWS As Worksheet
    Dim rng As Range, rngCopy As Range
    Dim lastRow As Long, i As Long, numCopied As Long
    
    Set baseWB = ThisWorkbook
    Set baseWS = baseWB.Sheets("Sheet1")
    
    ' open workbook to copy from
    Set spWB = Workbooks.Open("Source.xlsx", ReadOnly:=True)
    Set spWS = spWB.Sheets("Sheet1")
    numCopied = 0
    
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    With spWS
    
        lastRow = .Cells(.Rows.Count, "D").End(xlUp).Row
        For i = lastRow To 1 Step -1
            ' Sprawdz, czy w kolumnie C jest 0
            If .Cells(i, "C").Value <> 0 Then
                Set rng = .Cells(i, "A").Resize(, 30) ' A:AD
                If rngCopy Is Nothing Then
                    Set rngCopy = rng
                Else
                    Set rngCopy = Union(rng, rngCopy)
                End If
                numCopied = numCopied + 1
            End If
            If numCopied = 3 Then
                Exit For
            End If
        Next i
    End With
    
    ' copy
    If rngCopy Is Nothing Then
        MsgBox "No rows found to copy", vbExclamation
    Else
        rngCopy.Copy
        baseWS.Range("E5").PasteSpecial xlPasteValues
        Application.CutCopyMode = False
        MsgBox " Copied : " & rngCopy.Address, vbInformation
       
    End If
    spWB.Close SaveChanges:=False
     
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True

End Sub

相关问题