簡體   English   中英

VBA為什么不能正確地對列數據進行排序?

[英]Why isn't my VBA sorting my column data correctly?

我正在嘗試刪除Excel工作表的第一行,並使用其名稱“ CUST_RELPO”對特定列進行排序。 我正在使用列標題名稱,因為名稱可能會更改。

由於我確實需要復制列標題,因此對第二行的列進行排序和復制。

Sub ClearFirstRow()
'
' ClearFirstRow Macro
'

'
Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    Cells.Select
  Dim rngcustrelpo As Range
  xindex = Application.ActiveCell.Column
  Set rngcustrelpo = ActiveSheet.UsedRange.Find("CUST_RELPO")
  If rngcustrelpo Is Nothing Then
    MsgBox "CUST_RELPO column was not found."
    Exit Sub
    End If
    'Cells.Select
    Range(rngcustrelpo, rngcustrelpo.End(xlDown)).Select
    ActiveWorkbook.Worksheets("BACKORDER").Sort.SortFields.Add Key:=ActiveSheet.UsedRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("BACKORDER").Sort
        .SetRange ActiveSheet.UsedRange
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Set rngcustrelpo1 = rngcustrelpo.Offset(1, 0)
    Range(rngcustrelpo1, rngcustrelpo1.End(xlDown)).Select
    Selection.Copy
End Sub

但是,它並沒有像我期望的那樣對數據進行排序。 我不確定我在這里缺少什么。

Key:=ActiveSheet.UsedRange是對排序方法的完全誤解。 (Usedrange覆蓋了工作表上的整個已用區域-通常也為“空”單元格。). .SetRange ActiveSheet.UsedRange 沒必要,這還不錯。 當您想限制要排序的區域時,需要SetRange 如果您只想按一個鍵(列)排序,請更改此鍵

ActiveWorkbook.Worksheets("BACKORDER").Sort.SortFields.Add Key:=ActiveSheet.UsedRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("BACKORDER").Sort
    .SetRange ActiveSheet.UsedRange
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

對此:

With ActiveWorkbook.Worksheets("BACKORDER").Sort
    .Key rngcustrelpo
    .Header = xlYes
    .MatchCase = False
    .Order:=xlAscending
    .Orientation = xlTopToBottom
    .SortOn:=xlSortOnValues
    .DataOption:= xlSortTextAsNumbers
    .SortMethod = xlPinYin
    .Apply
End With

您可以在此處找到更多信息: Excel SortFields添加然后排序,並在這里: 排序和排序語法VBA的最有效方法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM