2014-11-21 95 views
1

我看來,當我運行的代碼,這個塊將得到一個錯誤1004半個月左右的時間,我根本不知道爲什麼:運行時錯誤1004的排序功能VBA

Dim ranged As Range 
Set ranged = Range("AJ2") 
Set ranged = Range(ranged, ranged.End(xlDown)) 


Sheets(i).Select 
ActiveWorkbook.Worksheets(i).Sort.SortFields.Add Key:=ranged, _ 
    SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal 
With ActiveWorkbook.Worksheets(i).Sort 
    .SetRange ranged 
    .Header = xlNo 
    .MatchCase = False 
    .Orientation = xlTopToBottom 
    .SortMethod = xlPinYin 
    .Apply 

End With 

的代碼是正在運行通過一系列工作表並且AJ列中的範圍在每個工作表上的大小不同,因此開始時的範圍定義是必要的。目標是顛倒範圍的順序。任何人都可以幫助解決錯誤嗎?

回答

0
  1. 在大多數情況下,您不需要選擇工作表。您可能想看到THIS

  2. 請勿使用xlDown構造您的範圍。使用xlUp通過查找包含數據的最後一行來完成。你可能想看到THIS

結合上述,你的代碼可以看起來像下面。請嘗試。 (UNTESTED

Dim ranged As Range 
Dim lRow As Long 

' 
'~~> Rest of the code 
' 

With ThisWorkbook.Sheets(i) 
    '~~> Find Last row in Col AJ which has data 
    lRow = .Range("AJ" & .Rows.Count).End(xlUp).Row 

    '~~> Construct your range 
    Set ranged = .Range("AJ2:AJ" & lRow) 

    '~~> Sort 
    .Sort.SortFields.Add Key:=ranged, _ 
         SortOn:=xlSortOnValues, _ 
         Order:=xlDescending, _ 
         DataOption:=xlSortNormal 
    With .Sort 
     .SetRange ranged 
     .Header = xlNo 
     .MatchCase = False 
     .Orientation = xlTopToBottom 
     .SortMethod = xlPinYin 
     .Apply 
    End With 
End With 

' 
'~~> Rest of the code 
' 

久經考驗的版本

Sub Sample() 
    Dim ranged As Range 
    Dim lRow As Long, i As Long 

    For i = 1 To ThisWorkbook.Sheets.Count 
     ' 
     '~~> Rest of the code 
     ' 

     With ThisWorkbook.Sheets(i) 
      '~~> Find Last row in Col AJ which has data 
      lRow = .Range("AJ" & .Rows.Count).End(xlUp).Row 

      '~~> Construct your range 
      Set ranged = .Range("AJ2:AJ" & lRow) 

      '~~> Sort 
      .Sort.SortFields.Add Key:=ranged, _ 
           SortOn:=xlSortOnValues, _ 
           Order:=xlDescending, _ 
           DataOption:=xlSortNormal 
      With .Sort 
       .SetRange ranged 
       .Header = xlNo 
       .MatchCase = False 
       .Orientation = xlTopToBottom 
       .SortMethod = xlPinYin 
       .Apply 
      End With 
     End With 

     ' 
     '~~> Rest of the code 
     ' 
    Next i 
End Sub 
+0

感謝您的幫助。我將此代碼完全複製到我的代碼中,它仍然出現「運行時錯誤1004:排序引用無效。請確保它位於要排序的數據中,並且第一個排序方框不是相同或空白。「奇怪的是,當我通過將ThisWorkbook.Sheets(i)更改爲With ThisWorkbook.Sheets(「Sheetname」)時,它在一張紙上運行時,它工作正常,但是當我將它放入上述結構中以運行多個根據你的代碼它沒有。有任何想法嗎? – mm123 2014-11-25 03:54:11