Copy a selected range to another worksheet

前端 未结 2 2060
眼角桃花
眼角桃花 2020-11-27 08:33

I am using code below which I am trying to change so as not to use .select

Selection.Select \' from active worksheet
    Selection.Copy
    Sheets(\"Purch Re         


        
2条回答
  •  粉色の甜心
    2020-11-27 09:02

    There is many ways to do that, but here goes two.

    1)

    Sub pasteExcel()
        Dim src2Range As Range
        Dim dest2Range As Range
        Dim r 'to store the last row
        Dim c 'to store the las column
        Set src2Range = Selection 'source from selected range
    
        r = Range("A1").End(xlDown).Row 'Get the last row from A1 to down
        c = Range("A1").End(xlToRight).Column 'Get the last Column from A1 to right
        Set dest2Range = Range(Cells(1, 1), Cells(r, c))
        dest2Range.PasteSpecial xlPasteAll
        Application.CutCopyMode = False 'Always use the sentence.
    End Sub
    

    2)

    Sub pasteExcel2()
        Dim sht1 As Worksheet
        Dim sht2 As Worksheet 'not used!
        Dim src2Range As Range
        Dim dest2Range As Range
        Dim r 'to store the last row
        Dim c 'to store the las column
    
        Set sht1 = Sheets("Sheet1")
        Set sht2 = Sheets("Sheet2")
    
        sht1.Activate 'Just in case... but not necesary
    
        r = Range("A1").End(xlDown).Row 'Get the last row from A1 to down
        c = Range("A1").End(xlToRight).Column 'Get the last Column from A1 to right
        Set src2Range = Range(Cells(1, 1), Cells(r, c)) 'source from selected range
        Set dest2Range = Range(Cells(1, 1), Cells(r, c))
        sht2.Range(dest2Range.Address).Value = src2Range.Value 'the same range in the other sheet. 
    End Sub
    

    Tell me if you need some improvement.

提交回复
热议问题