我在以下代码中遇到了ActiveWorkSheet.Sort.SortFields.Clear
行所需的运行时错误' 424':
Sub UpdateCharts()
'
' UpdateCharts Macro
'
' Keyboard Shortcut: Ctrl+u
'
Dim iIndex As Integer
Dim ws As Excel.Worksheet
For iIndex = 2 To ActiveWorkbook.Worksheets.Count
Set ws = Worksheets(iIndex)
ws.Activate
Range("AQ6:AS19").Select
Selection.Copy
Range("T6:V19").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
ActiveWorkSheet.Sort.SortFields.Clear
ActiveWorkSheet.Sort.SortFields.Add Key:=Range( _
"V6:V19"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkSheet.Sort
.SetRange Range("T6:V19")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("W5") = "=Today()"
Range("V5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("W5").Clear
Range("A1").Select
Next iIndex
End Sub
答案 0 :(得分:0)
使用ws
代替Activesheet清理了一下,显示了如何使用with ws
Sub Button1_Click()
Dim iIndex As Integer
Dim ws As Excel.Worksheet
For iIndex = 1 To ActiveWorkbook.Worksheets.Count
Set ws = Worksheets(iIndex)
With ws
.Range("AQ6:AS19").Copy
.Range("T6:V19").PasteSpecial xlPasteValues
Application.CutCopyMode = False
.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=.Range( _
"V6:V19"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With .Sort
.SetRange Range("T6:V19")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
.Range("W5") = "=Today()"
'Range("V5").PasteSpecial xlPasteValues ' you have nothing copied
.Range("W5").Clear
' .Range("A1").Select'don't select A1
End With
Next iIndex
End Sub