2013-01-13 57 views
1

隨着代碼正確的語法下面我得到一個錯誤:Excel中VBA排序不工作究竟是什麼worksheet.range參考

Run-time error '1004' Method 'Range' of object'_Worksheet failed.

Dim destLastCol As Integer 'last column in range 
    Dim destLastRow As Integer 'last row in range 
    Dim wsCrewDetail As Worksheet ' 

    Set wsCrewDetail = Worksheets("CrewDetail_M") 
    destLastCol = integer assigned previously 
    destLastRow = integer assigned previously 

    With wsCrewDetail.Range(Cells(4, 1), Cells(destLastRow, destLastCol)) <== error here 
    .Sort Key1:=.Cells(4, 2), Order1:=xlAscending, _ 
    key2:=.Cells(4, 1), Order2:=xlAscending, _ 
    key3:=.Cells(4, 3), order3:=xlAscending, Header:=xlYes 
    End With 

我搜索和瀏覽的例子很多很多努力在設置Range參考的變化,並沒有任何工作。

什麼是正確的參考語法?

編輯補充先前分配destLastRow =整數和編輯,以顯示destLastCol

+3

你沒有施放任何upvotes或接受任何答案。 –

+1

感謝您的提示,看起來有點upvotes和接受..我一直在尋找一些用戶界面功能來做到這一點..在評論的底部..或旁邊的用戶名..我剛剛假設我我只是第一次認識到/認識到巨大的(現在完全明顯但仍然坦率地有點不清楚......)上下三角形,複選標記是用戶界面功能給這個輸入)。我查看了我認爲會顯示正確答案的複選標記。點擊向上的三角形,我會假設移動迴應朝1,但將其向下移動。 – curtisp

+1

任何指針提示提示等熱烈歡迎! – curtisp

回答

4

那麼你不喂行數爲destLastRow在這一行
With wsCrewDetail.Range(Cells(4, 1), Cells(destLastRow, destLastCol))

另外,不要使用Integer變量,使用Long。他們更有效率,也適合大量人羣。使用較短的變量,如ws用於工作表使得Long而非Integer

  • 我將通常設定的工作範圍更容易地輸入和閱讀代碼
  • 使用

    建議

    • rng1)而不是使用從紙張開始的較長物體
    • 假人destLastRowdestLastCol個值

    示例代碼

    Dim destLastCol As Long 'last column in range 
        Dim destLastRow As Long 'last row in range 
        Dim ws As Worksheet 
        Dim rng1 As Range 
    
        Set ws = Worksheets("CrewDetail_M") 
        destLastCol = 6 
        destLastRow = 10 
    
        Set rng1 = ws.Range(ws.Cells(4, 1), ws.Cells(destLastRow, destLastCol)) 
        With rng1 
        .Sort Key1:=.Cells(4, 2), Order1:=xlAscending, _ 
        key2:=.Cells(4, 1), Order2:=xlAscending, _ 
        key3:=.Cells(4, 3), order3:=xlAscending, Header:=xlYes 
        End With 
    
  • +0

    應該在工作表中限定'Cell'調用 –

    +1

    + 1很好地解釋 –

    +0

    啊,「ws.Cells」語法是缺失的部分。非常感謝。我發誓我在Google的搜索記錄中沒有看到這種語法。在詢問之前,我會進行詳盡的搜索和迭代。我聽到你的其他建議。在我的使用案例中,我知道我會留在整數區域,並且在開發過程中我喜歡描述性變量名稱。然而,在某些時候,我通常會發現/替換使用更短的版本。 – curtisp