【发布时间】:2019-09-15 00:10:11
【问题描述】:
您会在下面看到一段代码,用于: 首先对数据列表进行排序,首先基于 Entity 列,第二个基于 GREN 列,第三个基于 IC 列。然后编译具有相同Entity、GREN和IC列的数据。
由于某种原因,我在运行代码时收到以下错误:
运行时错误“1004”:对象“_Global”的方法“Range”失败。
对其他列进行排序并没有失败,当我使用较少的数据时,它似乎工作得很好。有谁明白出了什么问题?更重要的是如何解决它?
Sub itest()
Dim EntityCol As Long, GRENCol As Long, ICCol As Long, ValueCol As Long, i As Long
Dim firstrow As Long, lastrow As Long, rngData As Range
Worksheets("FC_OUTPUT").Activate
Application.ScreenUpdating = False
EntityCol = 4 ' column D
GRENCol = 8
ICCol = 9
ValueCol = 12 ' column L
firstrow = 7
lastrow = Cells(Rows.Count, EntityCol).End(xlUp).Row
With ActiveSheet.Sort
.SortFields.Add Key:=Range(Cells(firstrow, EntityCol)), Order:=xlAscending
.SortFields.Add Key:=Range(Cells(firstrow, GRENCol)), Order:=xlAscending
.SortFields.Add Key:=Range(Cells(firstrow, ICCol)), Order:=xlAscending
.SetRange Range(Cells(firstrow, 1), Cells(lastrow, 96))
.Header = xlNo
.Apply
End With
Set rngData = Range(Cells(firstrow, 1), Cells(lastrow, 96)) ' this line should be adjusted but you'll need to also adjust firstrow and lastrow
With rngData
' Here I'll start a loop for every row going from the end to the beginning, to prevent issues when removing rows
For i = lastrow To firstrow Step -1
' Here I'll use the If statement to check if the values are the same as the previous row
If .Cells(i, EntityCol) = .Cells(i - 1, EntityCol) And _
.Cells(i, GRENCol) = .Cells(i - 1, GRENCol) And _
.Cells(i, ICCol) = .Cells(i - 1, ICCol) Then
' This is where you'll do your addition and delete
.Cells(i - 1, ValueCol).Value2 = .Cells(i - 1, ValueCol) + .Cells(i, ValueCol)
.Rows(i).Delete
End If
Next i
End With
End Sub
【问题讨论】:
标签: excel vba sorting columnsorting