Excel macro - paste only non empty cells from one sheet to another

后端 未结 3 759
梦毁少年i
梦毁少年i 2020-11-29 10:12

Below is the code which I am using to copy cells from one sheet and paste in to another.

Sheets(\"codes\").Select
Range(\"A5:A100\").Select
Selection.Copy
Sh         


        
3条回答
  •  温柔的废话
    2020-11-29 10:29

    If you don't need formatting I'd use the following. All it does is copy the range you specify on the worksheet to a variable, loop through that variable, check for cells that are empty and put in whatever string you like. It's nice and quick. If you want to preserve the formatting, you can paste special just the formats to the output range.

    Sub CopyNonBlankCells(rFromRange As Range, rToCell As Range, sSubIn As String)
        'You have three inputs.  A range to copy from (rFromRange), a range to copy to (rToCell) and a string to put in the blank cells.        
    
        Dim vData As Variant, ii As Integer, jj As Integer
    
       'Set to a variable since it's quicker
        vData = rFromRange.Value
    
        'Loop through to find the blank cells
        For ii = LBound(vData, 1) To UBound(vData, 1)   'Loop the rows
            For jj = LBound(vData, 2) To UBound(vData, 2)    'Loop the columns
                'Check for empty cell.  Quicker to use Len function then check for empty string
                If VBA.Len(vData(ii, jj)) = 0 Then vData(ii, jj) = sSubIn
            Next jj
        Next ii
    
        'Output to target cell.  Use the 'With' statement because it makes the code easier to read and is more efficient
        With rToCell.Parent
            .Range(.Cells(rToCell.Row, rToCell.Column), .Cells(rToCell.Row + UBound(vData, 1) - 1, rToCell.Column + UBound(vData, 2) - 1)).Value = vData
        End With
    
    End Sub
    

    And call it with:

    Call CopyNonBlankCells(Sheets("codes").Range("A5:A100"), Sheets("Sheet2").Range("B28"), "Non-blank")
    

提交回复
热议问题