简体   繁体   中英

Copy & Paste range as values into next empty column on another sheet

I am trying to copy a range (which varies based on inputs) as values into another sheet.
The code below seems to be copying on top of the last entry rather than into the next empty column.

Sub CommandButton3_Click()
    
    Dim source As Worksheet
    Dim destination As Worksheet
    Dim emptyColumn As Long
        
    Set source = Sheets("Month Template")
    Set destination = Sheets("Sheet1")
        
    'find empty Column (actually cell in Row 1)'
    emptyColumn = destination.Cells(1, destination.Columns.Count).End(xlToLeft).Column
    If emptyColumn > 1 Then
        emptyColumn = emptyColumn + 1
    End If
    
    source.Range("m26:m35").Copy destination.Cells(1, emptyColumn)
    
End Sub

try with below

Sub CommandButton3_Click()
    Dim source As Worksheet
    Dim destination As Worksheet
    Dim emptyColumn As Long
    Set source = Sheets("Month Template")
    Set destination = Sheets("Sheet1")
    'find empty Column (actually cell in Row 1)'
    emptyColumn = destination.Cells(1, 1).End(xlToRight).Column
    If emptyColumn > 1 Then
        emptyColumn = emptyColumn + 1
    End If
    source.Range("m26:m35").Copy destination.Cells(1, emptyColumn)
End Sub

This is an old question that popped up. When reading the Op's question, it looks like they want to make sure the 1st column is used and then move over to column 2.

If emptyColumn > 1 Then

When 1st using the copy&paste code emptycolumn will never be greater than 1.

A possible solution would be to 1st check if A1 ="" when emptycolumn=2.

Private Sub CommandButton3_Click()
    Dim source As Worksheet
    Dim destination As Worksheet
    Dim emptyColumn As Long

    Set source = Sheets("Month Template")
    Set destination = Sheets("Sheet1")

    'find empty Column (actually cell in Row 1)'
    emptyColumn = destination.Cells(1, destination.Columns.Count).End(xlToLeft).Column + 1

    If destination.Cells(1, 1) = "" And emptyColumn = 2 Then emptyColumn = 1

    source.Range("m26:m35").Copy destination.Cells(1, emptyColumn)

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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