如何使用excel宏对空单元格进行排序?

时间:2015-11-30 06:41:54

标签: excel vba excel-vba sorting

非常感谢您阅读我的问题。我试图在stackoverflow中搜索类似的问题,但未能得到答案...非常感谢你能帮助我。

我的目的是将数据从表格(“部分”)复制并粘贴到表格(“摘要”),然后按A列排序,忽略空单元格。

A1: 2.1

A2: 

A3: 1.1

A4: 1.2

排序后:

A1: 1.1

A2: 1.2

A3: 2.1

A4:  

宏在“宏”构建器中成功,但在工作表中失败(第一行为空)。事实上,我试图不用“SkipBlanks”复制空单元格而不是功能......

Sub IEMacro()
Dim Lastcell As Range

Sheets("Parts").Range("A3:A300").Copy

With Sheets("Summary")
Set Lastcell = .Range("A65536").End(xlUp)
.Range("A2", Lastcell).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,     SkipBlanks:=True, Transpose:=False
.Range("A2", Lastcell).Sort Key1:=ActiveCell, Order1:=xlAscending, Header:=xlGuess
End With

2 个答案:

答案 0 :(得分:0)

在这种情况下,您需要选择完整的范围,直到数据的最后一列,然后按升序排序,然后自动选择自动过滤器。



Sub sort()
'selecting complete range change it as required
    Range("A1:O12").Select
' Replace the sheet name with yours
    ActiveWorkbook.Worksheets("Sheet1").sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").sort.SortFields.Add Key:=Range("A1"), _
        SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").sort
    'sorting complete range change it as required
        .SetRange Range("A1:O11")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub




答案 1 :(得分:0)

这应该正确应用排序键:

Sub IEMacro()
Dim LastCell As Range

Sheets("Parts").Range("A3:A300").Copy

With Sheets("Summary")
    Set LastCell = .Range("A" & .Rows.count).End(xlUp)
    .Range("A2").PasteSpecial Paste:=xlPasteValues, _
                                        Operation:=xlNone, _
                                        SkipBlanks:=True, _
                                        Transpose:=False
    With .Sort
        .SortFields.Clear
        .SortFields.Add Key:=Sheets("Summary").Range(Sheets("Summary").Range("A1"), LastCell), _
                        SortOn:=xlSortOnValues, _
                        Order:=xlAscending, _
                        DataOption:=xlSortNormal
        .SetRange Sheets("Summary").Range(Sheets("Summary").Range("A1"), LastCell)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End With

End Sub