VBA - 如果单元格不为空,则复制范围

时间:2018-03-28 16:13:43

标签: excel excel-vba vba

我目前有这段代码:

Sub createSheets(range_Copy As Range, range_Paste As Range)
    'Copy the data
    range_Copy.Copy

    'Paste the data into the new worksheet
    With range_Paste
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With
End Sub

......而这......

Call createSheets(Sheets("Export from QB - Annual Sales").Range("E:T"), Sheets("Sales - " & Sales_Date_Annual).Range("A1"))

它工作得很好但我真正想做的是......当复制范围E:T时,我只想复制E列中没有空白值的行...无论是否有什么在其他栏目中。

1 个答案:

答案 0 :(得分:0)

我认为以下代码会对您有所帮助。这里有用的信息是,您可以使用相对引用引用范围中的单元格,即Range("D4:E6").Cells(1, 1)是对单元格D4的引用。通过这种方式,您可以轻松地遍历给定范围。

Sub LoppthroughRange()
Dim i As Long, j As Long, rng As Range
Set rng = Range("E:T")
For i = 1 To rng.Rows.Count
    If Not IsEmpty(rng.Cells(i, 1)) Then
        For j = 1 To rng.Columns.Count
            'copy all cells in a row
        Next
    End If
Next

End Sub

总而言之,你应该使用:

Sub createSheets(range_Copy As Range, range_Paste As Range)
    Dim i As Long, j As Long, k As Long
    k = 1

    For i = 1 To range_Copy.Rows.Count
        If Not IsEmpty(range_Copy.Cells(i, 1)) Then
            With range_Copy
                .Range(Cells(i, 1), Cells(i, .Columns.Count)).Copy
            End With
            With range_Paste
                .Range(Cells(k, 1), Cells(k, .Columns.Count)).PasteSpecial xlValues
                .Range(Cells(k, 1), Cells(k, .Columns.Count)).PasteSpecial xlFormats
            End With
            k = k + 1
        End If
    Next
End Sub