我有一个Excel VBA宏,它在前两次运行时成功运行,但第三次出现此错误:
运行时错误' 1004'
排序参考无效。确保它在您要排序的数据中,并且第一个“排序方式”框不是相同或空白。
如果我重新启动Excel,它会在前两次运行,然后再次给出错误。为什么会这样?这是我的代码:
Dim rawData As Object
Dim report As Object
Dim areaCodes As Object
Set rawData = Sheets("RawData")
Set report = Sheets("Report")
Set areaCodes = Sheets("AreaCodes")
report.Cells.Clear
report.Cells.ClearFormats
stateCol = rawData.Cells(1, 1).EntireRow.Find(What:="state", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
Dim MyRange As Range
Set MyRange = rawData.Cells(1, stateCol)
With rawData
lastRow = .Cells(Rows.Count, MyRange.Column).End(xlUp).Row
.Range(.Cells(2, stateCol), .Cells(lastRow, stateCol)).Copy
End With
With report
.Range("A3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
.Range(.Cells(3, 1), .Cells(lastRow + 1, 1)).RemoveDuplicates Columns:=1, Header:=xlNo
End With
lastRow = report.Cells(Rows.Count, Range("A1").Column).End(xlUp).Row
report.Range("B3").Select
ActiveCell.FormulaR1C1 = "=COUNTIF(rawData!C[" & stateCol - 2 & "],report!RC[-1])"
Range("B3").AutoFill Destination:=Range("B3:B" & lastRow)
Range("B" & lastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R[-" & lastRow - 2 & "]C:R[-1]C)"
Range("C3").Select
ActiveCell.FormulaR1C1 = "=RC[-1]/R" & lastRow + 1 & "C[-1]"
Range("C3").AutoFill Destination:=Range("C3:C" & lastRow)
Range("C" & lastRow + 1).Select
ActiveCell.FormulaR1C1 = "=SUM(R[-" & lastRow - 2 & "]C:R[-1]C)"
Range("C:C").NumberFormat = "0.0%"
Range("A2:A" & lastRow + 1).Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
report.Range("A2").Value = "State"
report.Range("A2").Font.Bold = True
report.Range("A:A").HorizontalAlignment = xlCenter
report.Range("A3").FormulaR1C1 = "=INDEX(areaCodes!R2C5:R52C5,MATCH(report!RC[1],AreaCodes!R2C6:R52C6,0))"
Range("A3").Select
ActiveCell.AutoFill Destination:=Range("A3:A" & lastRow)
With report
newLastRow = .Cells(Rows.Count, Range("C1").Column).End(xlUp).Row - 1
.Range(.Cells(3, 3), .Cells(newLastRow, 3)).Copy
.Range("C3").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End With
With report
.Sort.SortFields.Add Key:=Range("C2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
newLastRow = .Cells(Rows.Count, Range("C1").Column).End(xlUp).Row - 1
With .Sort
.SetRange Range("A2:D" & newLastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
答案 0 :(得分:1)
您应该在排序说明中限定范围,如果未激活工作表报告,这将产生错误
With report
.Sort.SortFields.Add Key:=.Range("C2"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
newLastRow = .Cells(Rows.Count, .Range("C1").Column).End(xlUp).Row - 1
With .Sort
.SetRange report.Range("A2:D" & newLastRow)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With