一次对数字和文本进行排序会产生问题

时间:2016-04-21 14:02:31

标签: vba excel-vba sorting macros excel

我有一个问题。我正在从一个大型产品表(大约32行和3900行)中过滤掉我需要的产品,然后按产品名称和发货编号对其进行排序。

我的问题是,如果我想过滤和排序数字作为产品名称(这也是可能的),它就不能正确排序(见图片)。

Picture of the filtered and sorted table

我的代码就是这个:

'*************************************************************
'Filter Product Code
Set myrange = Range("A1:A" & lastrow)

For Each c In myrange
    If Len(c.Value) <> 0 Then
                ThisWorkbook.Worksheets(Worksheets.Count).Columns("A:D").AdvancedFilter xlFilterCopy, _
            Sheet1.Range("A1:A" & lastrow), Sheet1.Range("G1"), False
    End If
Next

'Sheet1.Range("51:100").RemoveDuplicates Columns:=3, Header:=xlYes

'*******************************************************************
'Sort the filtered list first by Product Code then by the Delivery number
Dim lngRow As Long
Dim lngRowMax As Long
Dim wsf As WorksheetFunction

With Sheet1

lastrow = Cells(Rows.Count, 8).End(xlUp).Row

Range("G2:J" & lastrow).Sort Key1:=Range("G2:G" & lastrow), _
 Order1:=xlAscending, Key2:=Range("I2:I" & lastrow), _
 Order1:=xlAscending, Header:=xlNo

Set wsf = Application.WorksheetFunction
lngRowMax = .UsedRange.Rows.Count

End With

如何进行正确排序。首先是相同的产品代码,然后是交货编号(升序),因为我想先销售最老的产品。

感谢您的回复。

1 个答案:

答案 0 :(得分:0)

现在我找到了解决方案。只是一个小调整。现在,排序代码如下所示:

Dim lngRow As Long
Dim lngRowMax As Long
Dim wsf As WorksheetFunction

 With Sheet1

lastrow = Cells(Rows.Count, 8).End(xlUp).Row

Range("G1:J" & lastrow).Sort Key1:=Range("G1:G" & lastrow), _
   Order1:=xlAscending, Key2:=Range("I1:I" & lastrow), _
   Order2:=xlAscending, Header:=xlYes, DataOption1:=xlSortTextAsNumbers


Set wsf = Application.WorksheetFunction
lngRowMax = .UsedRange.Rows.Count

End With