VBA运行时错误1004 Range类的排序方法失败



我最近开始为一家公司工作,这家公司最近收购了另一家使用VBA和excel宏的公司。我在这些事情上几乎没有经验,但我的任务是修复错误,虽然我已经能够调试一些问题,但这个问题却把我难住了。

下面是导致错误的代码:

lastrow = ActiveSheet.Cells(Rows.count, 1).End(xlUp).Row
WorkRange = "A1:BB" & lastrow
Range(WorkRange).Sort Key1:=Range("C2"), Order1:=xlAscending, Header:=xlYes

任何帮助都是感激的,我很乐意提供任何可能需要的其他信息。

Sort a (Table) Range

Option Explicit
Sub SortRange()
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
' If this worksheet is in the workbook containing this code,
' then in the VBE Project Explorer, you can identify its names,
' e.g. 'Sheet1 (Data)' where 'Data' is its tab name while 'Sheet1'
' is its code name. Then you can more safely reference the worksheet
' with either 'Set ws = ThisWorkbook.Worksheets("Data")'
' or use the safest option by removing the previous line and instead of 'ws'
' just using 'Sheet1' in the continuation of the code. In the latter
' case, the code will still work correctly if someone decides that
' 'Calculation' is a better (tab) name then 'Data'.
' Calculate the last row ('LastRow').
Dim LastRow As Long: LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' Reference the range ('rg').
Dim rg As Range: Set rg = ws.Range("A1:BB" & LastRow)
' Sort the range.
rg.Sort rg.Columns(3), xlAscending, , , , , , xlYes
' If you have nice table data i.e. starting in cell 'A1', one row of headers
' and no empty rows or columns, you can shorten the code by using...
'Dim rg As Range: Set rg = ws.Range("A1").CurrentRegion
'rg.Sort rg.Columns(3), xlAscending, , , , , , xlYes
' ... when the last row is not necessary.

' The last option, when using the code name e.g. 'Sheet1',
' would require only...
'Dim rg As Range: Set rg = Sheet1.Range("A1").CurrentRegion
'rg.Sort rg.Columns(3), xlAscending, , , , , , xlYes
' ... without the worksheet declaration.
End Sub

相关内容

  • 没有找到相关文章

最新更新