2016-08-12 176 views
1

我在排序時遇到了一些問題。有趣的是,這是工作,直到我試圖添加一些選項到Range.sort函數(我已經刪除)。給出的錯誤代碼是「運行時錯誤'1004':範圍類失敗的排序方法」。我已經在下面發佈了我的代碼,但我無法確定排序失敗的原因。我查看了所有的列和行值,它們都是正確的。它試圖在我的工作表上對「B2:B39」進行排序。我還附上了隱藏變量表的圖片,以顯示輸出的樣子,直到排序失敗。Excel VBA排序失敗

編輯:爲了澄清,我已嘗試複製,刪除唯一身份證,然後在第一行行中排序,但無論如何我都會得到相同的錯誤。功能最後一次工作時,我相信範圍確實從第二行開始。

Output range I'm trying to sort

Sub addUniques() 
    Dim i As Long 
    For i = 2 To 9 
     Call copyColToSheet(ThisWorkbook.Sheets("CallLog"), ThisWorkbook.Sheets("HiddenVariables"), NumToLet(i), NumToLet(i)) 
    Next i 
End Sub 

Function copyColToSheet(wsSource As Worksheet, wsDest As Worksheet, colSource As String, colDest As String) 
    wsSource.Range(colSource & "2:" & colSource & CStr(getLastRowInCol(wsSource, colSource))).Copy wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))) 
    wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))).RemoveDuplicates Columns:=1, Header:=xlNo 
    wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))).Sort 
End Function 

Function getLastRowInCol(ws As Worksheet, col As String) As Long 
    With ws 
     getLastRowInCol = .Range(col & .Rows.Count).End(xlUp).Row 
    End With 
End Function 

Function NumToLet(lngCol As Long) As String 
    Dim vArr 
    vArr = Split(Cells(1, lngCol).Address(True, False), "$") 
    NumToLet = vArr(0) 
End Function 

回答

1

我認爲你需要設置一個關鍵

試試這個:

Function copyColToSheet(wsSource As Worksheet, wsDest As Worksheet, colSource As String, colDest As String) 
wsSource.Range(colSource & "2:" & colSource & CStr(getLastRowInCol(wsSource, colSource))).Copy wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))) 
wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))).RemoveDuplicates Columns:=1, Header:=xlNo 
wsDest.Range(colDest & "2:" & colDest & CStr(getLastRowInCol(wsDest, colDest))).Sort Key1:=wsDest.Range(colDest & "2") 
End Function 
+0

是的,就是這樣。感謝您的幫助。 – RWA4ARC