Exclude some columns while copying one row to other

后端 未结 3 668
孤街浪徒
孤街浪徒 2020-12-21 15:28

I want to copy contents of one row in Excel to other row.

Currently, I am using following code for copying data from previous row.

rngCurrent.Offse         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-21 15:43

    Another way of doing it.....takes less no. of loops.

    Assumptions
    1. Skip columns are in ascending order.
    2. Skip columns value starts from 1 and not 0.
    3. Range("Source") is First cell in source data.
    4. Range("Target") is First cell in target data.

    Sub SelectiveCopy(rngSource As Range, rngTarget As Range, intTotalColumns As Integer, skipColumnsArray As Variant)
    
    If UBound(skipColumnsArray) = -1 Then
        rngSource.Resize(1, intTotalColumns).Copy
        rngTarget.PasteSpecial (xlPasteValues)
    Else
    
        Dim skipColumn As Variant
        Dim currentColumn As Integer
    
        currentColumn = 0
    
        For Each skipColumn In skipColumnsArray
            If skipColumn - currentColumn > 1 Then 'Number of colums to copy is Nonzero.'
                rngSource.Offset(0, currentColumn).Resize(1, skipColumn - currentColumn - 1).Copy
                rngTarget.Offset(0, currentColumn).PasteSpecial (xlPasteValues)
            End If
    
            currentColumn = skipColumn
        Next
    
        If intTotalColumns - currentColumn > 0 Then
            rngSource.Offset(0, currentColumn).Resize(1, intTotalColumns - currentColumn).Copy
            rngTarget.Offset(0, currentColumn).PasteSpecial (xlPasteValues)
        End If
    
    End If
    
    Application.CutCopyMode = False
    
    End Sub
    

    How to call :

    SelectiveCopy Range("Source"), Range("Target"), 20, Array(1)     'Skip 1st column'
    SelectiveCopy Range("Source"), Range("Target"), 20, Array(4,5,6) 'Skip 4,5,6th column'
    SelectiveCopy Range("Source"), Range("Target"), 20, Array()      'Dont skip any column. Copy all.
    

    Thanks.

提交回复
热议问题