2014-10-02 37 views
0

我有一個表中的標題和從A到D的列中的數據隨着行號的變化(行數超過66800)。我想從Z到A的數據按列C排列。如何在VBA中進行排序?

在互聯網上有很多不同的VBA解決方案,但是沒有一個能夠爲我正確工作。

我的代碼給我一個錯誤:

Sub SortDescending() 
Dim lRow As Long 
Dim lCol As Long 
lRow = Sheets("atm_hh").Cells(Rows.Count, 1).End(xlUp).Row 
lCol = Sheets("atm_hh").Cells(1, Columns.Count).End(xlToLeft).Column 

    With Sheets("atm_hh") 
    .Select 
    .Range("A2:" & Cells(lRow, lCol).Address).Sort Key1:=Range("C2"), _ 
               Order1:=xlDescending, _ 
               Header:=xlGuess, _ 
               OrderCustom:=1, _ 
               MatchCase:=False, _ 
               Orientation:=xlTopToBottom 
    End With 
End Sub 
+0

你得到了什麼錯誤? – 2014-10-02 14:39:18

+0

我的意思不是VBA錯誤,但在Excel中,C列的排序錯誤。例如,9,99大於33,45等。 – Ale 2014-10-02 14:42:12

+0

也許excel不能識別您的語言環境中的逗號,並且您需要使用點作爲千位分隔符? – 2014-10-02 14:43:31

回答

0

嘗試

Sub SortDescending() 

    Dim sh As Worksheet 
    Set sh = Sheets("atm_hh") 

    Dim lRow As Long 
    Dim lCol As Long 
    lRow = sh.Cells(Rows.Count, 1).End(xlUp).Row 
    lCol = sh.Cells(1, Columns.Count).End(xlToLeft).Column 

    Dim cell As Range 
    For Each cell In sh.Range("C2:C" & lRow) 
     cell = WorksheetFunction.Substitute(cell, ",", ".") 
    Next 

    Columns("C:C").NumberFormat = "0.0" 

    sh.Cells.AutoFilter 
    sh.AutoFilter.Sort.SortFields.Clear 
    sh.AutoFilter.Sort.SortFields.Add Key:=Range("C1:C" & lRow), _ 
     SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal 
    With sh.AutoFilter.Sort 
     .Header = xlYes 
     .MatchCase = False 
     .Orientation = xlTopToBottom 
     .SortMethod = xlPinYin 
     .Apply 
    End With 
    sh.AutoFilterMode = False 
End Sub 
+0

它可以工作,但是對於列(「C:C 「).NumberFormat =」0「它將0.55設置爲55.我應該使用列(」C:C「)。NumberFormat =」0.0「? – Ale 2014-10-02 15:11:45

+0

如果你想要前面的零是啊 – 2014-10-02 15:14:13

+0

well 55和0.55是不一樣的,我需要以正確的方式保存數據,因此我需要總結它們,我需要0.00格式的數據。沒關係,我的意思是它不會改變價值嗎? – Ale 2014-10-02 15:16:23