【问题标题】:VBA AZ sort not working correctlyVBA AZ 排序无法正常工作
【发布时间】:2017-01-13 18:16:31
【问题描述】:

希望你能帮上忙。 我有一段代码打开一个对话框,然后允许用户选择另一个 Excel 工作表,然后一旦选择了该 Excel 工作表,就会调用另一段代码,并按字母顺序对 B 列进行排序。

我遇到的问题是 VBA 代码没有正确进行排序

如果我通过单击 AZ 排序按钮手动对列进行排序,我会在图 1 中得到结果

图 1

但是当我运行代码以按字母顺序对 B 列进行排序时。我在图 2 中得到结果

图 2

如您所见,顶部条目不正确,Anne Mette Toftager 没有正确排序,第二个条目仍然在第 83 行的工作表下方

我的代码如下。可以修改我的代码以使排序正常工作并且结果与图 1 中的结果相同吗?

一如既往地非常感谢任何帮助。

PS 我应该指出,VBA 排序还必须“扩展选择”

我的代码

Sub Open_Workbook_Dialog()

Dim my_FileName As Variant

    MsgBox "Select Denmark File" '<--| txt box for prompt to pick a file

        my_FileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*;*.xm*") '<--| Opens the file window to allow selection

    If my_FileName <> False Then
    Workbooks.Open Filename:=my_FileName


Call SortColumn     '<--|Calls the Filter Code and executes

End If


End Sub

Public Sub SortColumn()
    With ActiveWorkbook.Sheets(1)

    .Unprotect
    lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    .Range("A1").Resize(79, lastcol).Sort Key1:=Range("B1"), _
    Order1:=xlAscending, _
    Header:=xlGuess, _
    OrderCustom:=1, _
    MatchCase:=False, _
    Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal
End With
End Sub

【问题讨论】:

  • 您提到您的数据仍保留在“表格下方的第 83 行”。在您的 SortColumn 代码中,您只调整了第 79 行的大小 - 您的数据在哪一行结束?
  • 嗨,乔丹:我的数据在第 151 行结束。但每天可能会有所不同
  • 创建一个 lastrow 变量,就像您为您的 lastcol 设置的那样,然后使用它来调整大小而不是常量 79。例如,在您设置 lastcol 变量的位置下方添加:@ 987654330@ 然后将您的排序更改为:.Range("A1").Resize(lastrow, lastcol).Sort
  • @乔丹:嘘!这让它完美地工作。非常感谢你的帮助。非常感谢。都柏林非常尊重。我如何在 Stack 上给你一些积分?我只是在这个问题的开头选择正确的标记吗?我不想让你错过。
  • 别担心,我是来帮忙的,不是为了积分!

标签: vba excel sorting


【解决方案1】:

这应该可以工作

Sub SortColumn()

    With ActiveWorkbook.Sheets(1)

        Dim LastRow As Long
        LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
        Dim LastCol As Long
        LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
        With ActiveWorkbook.Worksheets("Sheet1").Sort
            .SortFields.Clear
            .SortFields.Add Key:=Range(Cells(2, 2), Cells(LastRow, 2)), _
                            SortOn:=xlSortOnValues, _
                            Order:=xlAscending, _
                            DataOption:=xlSortNormal
            .SetRange Range(Cells(2, 1), Cells(LastRow, LastCol))
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply

        End With

    End With
End Sub

【讨论】:

  • 嗨,Jean:是的,这非常有效,我唯一要做的更改是将 Dim LastRow As Long 更改为 Dim LastRow2 As Long,因为我已经在代码中进一步处理了 Dim LastRow as Long。还必须将行 LastRow = .Cells(Rows.Count, 1).End(xlUp).Row 更改为 LastRow2 = .Cells(Rows.Count, 1).End(xlUp).Row 但我到了那里。 :-) 乔丹以前让我去那里,但他不想要积分,所以我很高兴接受你的回答。非常感谢您抽出宝贵的时间。祝你有美好的一天
  • @PhilipConnell 好东西。互相帮助就是它的意义
猜你喜欢
  • 2018-07-18
  • 1970-01-01
  • 2020-12-14
  • 2012-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
相关资源
最近更新 更多