VBA AZsorting不正确

我希望你能帮上忙。 我有一段代码打开一个对话框,然后允许用户select另一个Excel工作表,然后一旦Excel工作表被选中,另一段代码被调用,它按字母顺序排列B列。

我遇到的问题是这种sorting不能正确使用VBA代码

如果我通过点击AZsortingbutton手动对列进行sorting,我将在图1中看到结果

图1

在这里输入图像说明

但是,当我运行代码按字母顺序sortingB列。 我在图2中得到结果

图2 在这里输入图像说明

正如你所看到的,最上面的条目是不正确的,Anne Mette Toftager没有被正确地sorting,第二个条目在第83行

我的代码如下。 我的代码可以修改,使sorting工作正确,结果与图1相同的结果?

像往常一样,任何帮助,不胜感激。

PS我应该指出,VBAsorting还必须“扩大select”

我的代码

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 

这应该工作

 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