简体   繁体   English

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

[英]VBA - Copy Range if cell not empty

I currently have this code: 我目前有以下代码:

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

...and this... ...和这个...

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

It works great but what I actually want to do is... when copying the range E:T, I only want to copy the rows that do not have a blank value in column E... regardless if there is anything in the other columns. 效果很好,但是我真正想做的是...复制范围E:T时,我只想复制E列中没有空值的行...不管其他行中是否有任何内容列。

I think below code will help you. 我认为以下代码将为您提供帮助。 Useful information here is, that you can reference a cell in a range using relative reference, ie Range("D4:E6").Cells(1, 1) is reference to cell D4 . 有用的信息是,您可以使用相对引用来引用某个范围内的单元格,即Range("D4:E6").Cells(1, 1)是对单元格D4引用。 This way you can easily loop through given range. 这样,您可以轻松遍历给定范围。

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

Putting it all together, you should use: 放在一起,您应该使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM