excel - 将整个工作表排序到最后一行

标签 excel vba sorting error-handling

我有一个宏,可以根据自定义排序对我的所有数据进行排序,但是如果要这么说,我想在具有不同的最后一行“数字”的不同工作表上使用它,并且我在这里有以下代码,但是我一直遇到错误:

只是为了让您知道我正在对O列进行排序

Sub SortDays()

' SortDays Macro



lRow = Worksheets("Banner Summary").Cells(Rows.Count, "B").End(xlUp).Row
Range("B1").Select
Range("A1:A" & lRow).Select
Range("O2").Activate
ActiveWorkbook.Worksheets("Banner Summary").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Banner Summary").Sort.SortFields.Add Key:=Range( _
    "O2:O" & lRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
    "M,T,W,R,F", DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Banner Summary").Sort
    .SetRange Range("A1:A" & lRow)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
End Sub

错误为:“排序引用无效。请确保...。”
它很长,所以我们将不胜感激,并且提前谢谢^ _ ^

最佳答案

传递您要排序的工作表:

Sub SortDays(byRef ws)

' SortDays Macro
lRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
'Range("B1").Select
'Range("A1:A" & lRow).Select
'Range("O2").Activate
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=Range( _
    "O2:O" & lRow), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
    "M,T,W,R,F", DataOption:=xlSortNormal
With ws.Sort
    .SetRange Range("A1:O" & lRow)
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
End Sub

然后,它将在您传递给它的任何工作表上运行(假设您已将ws定义为无论如何都要使用的工作表:
Dim ws As Worksheet : Set ws = Workbooks("excelfilename").Worksheets("WhateverSheet")

在使用Sub调用SortDays ws之前

关于excel - 将整个工作表排序到最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37924802/

相关文章:

Excel VBA 使用 CDO 添加附件时出错。消息 "Object doesn' t 支持此属性或方法"

ruby - 为什么我们可以在 block 中使用数组索引来在ruby中进行哈希排序?

java - 使用自定义起点对 ArrayList 对象属性进行排序

excel - 在 VS Code 中运行 PowerShell 脚本时出错,但在 PowerShell ISE 中运行良好

.net - 如何在VB.net应用程序中获取最新版本MS Excel的引用?

vba - Access 2007 VBA : how to get/change the current record's position on the screen

excel - 错误 - VBA 对象不支持此属性或方法

excel - VBA 架构技巧 - 宏封装

java打开文件并排序数据

excel - 如果单元格包含的日期小于今天,则设置单元格格式