Sort a Range before pasting Excel VBA

落爺英雄遲暮 提交于 2020-01-05 06:54:30

问题


I'm using the following code to copy a particular range from a Workbook to another Workbook, its working fine.

But now i need to sort the Range in ascending order just before pasting to the destination sheet without changing the source. Please help.

With Workbooks(strExcelFile).Sheets(strSheetName)
     .Range(strRange).Copy
End With

ActiveSheet.Range(strDestCell).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=False

回答1:


Take advantage of the fact that once you paste, your newly pasted range will be selected; then you can use SELECTION.

Public Sub test()
     Range("A1:A8").Copy
    ActiveSheet.Range("B1").PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
    False, Transpose:=False
    Selection.Sort key1:=Range("B1")
End Sub

That test example will work in any excel file with some data in A1-A8. B1 in both places can be replaced with strDestCell and A1:A8 with strRange for your eventual subroutine.




回答2:


You should try to avoid the redundant Select when working with ranges. You can work more cleanly using worksheets and ranges as below, which is easily adaptable accross workbooks as per your question

code

Sub ReCut()
    Dim ws1 As Worksheet
    Dim ws2 As Worksheet
    Dim rng1 As Range
    Set ws1 = ThisWorkbook.Sheets(1)
    Set ws2 = ThisWorkbook.Sheets(2)
    Set rng1 = ws1.Range("A1:A10")
    With ws2.[b1].Resize(rng1.Rows.Count, 1)
        .Value = rng1.Value
        .Sort ws2.[b1]
    End With
End Sub


来源:https://stackoverflow.com/questions/15017717/sort-a-range-before-pasting-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!