2017-01-12 126 views
0

在這個用戶的形式排序不工作

enter image description here

我有以下代碼(升序默認是TRUE,而降序爲False)

Private Sub OKButton_Click() 
Dim rRange As Range 
lastRow = Sheets("overview").Range("G1000").End(xlUp).Row 
On Error Resume Next 
Application.DisplayAlerts = False 
Set rRange = Application.InputBox(Prompt:="Please select a cell in the column you want 
_to sort", Title:="SPECIFY COLUMN", Type:=8) 
Col = rRange.Columns(1).Column 
On Error GoTo 0 
Application.DisplayAlerts = True 
If rRange Is Nothing Then 
    Exit Sub 
Else 
    If AscendingOption Then 
     Range("A14:CB" & lastRow).Sort key1:=Range(Col & "14:" & Col & lastRow), Order1:=xlAscending, Header:=xlNo, key2:=Range("C14:C" & lastRow), Order2:=xlAscending, Header:=xlNo 
    End If 
    If DescendingOption Then 
     Range("A14:CB" & lastRow).Sort key1:=Range(Col & "14:" & Col & lastRow), Order1:=xlDescending, key2:=Range("C14:C" & lastRow), Order2:=xlAscending   
    End If 
End If 
End Sub 

當我點擊確定沒有任何反應:不是錯誤信息,也不是任何行動。 任何人都可以幫我找到錯誤嗎?

+0

什麼'AscendingOption'和'DescendingOption'? – Limak

+0

據我所知'AscendingOption'和'DescendingOption'沒有預先定義,所以如果你沒有在你的'Sub'中定義它們,它們將永遠是'False'。 –

+0

您可能需要將'AscendingOption'和'DescendingOption'設置爲全局變量。正如Tom所說,這個變量在這個'Sub'中沒有定義。如果你想測試,在代碼的開頭添加'Option Explicit'行。當您再次運行程序時,應該會出現錯誤。 –

回答

0

這是正常工作的代碼版本:

Private Sub OKButton_Click() 
Dim rRange As Range 
lastRow = Sheets("overview").Range("G1000").End(xlUp).Row 
Application.DisplayAlerts = False 
Set rRange = Application.InputBox(Prompt:="Please select a cell in the column 
_you want to sort", Title:="SPECIFY COLUMN", Type:=8) 
Col = rRange.Columns(1).Column 
On Error GoTo 0 
Application.DisplayAlerts = True 
If rRange Is Nothing Then 
    Exit Sub 
Else 
    If AscendingOption Then 
     Range("A14:CE" & lastRow).Sort key1:=Range(Cells(14, Col), Cells(lastRow, Col)), 
     _Order1:=xlAscending, Header:=xlNo, key2:=Range("C14:C" & lastRow), 
     _Order2:=xlAscending, Header:=xlNo 
    End If 
    If DescendingOption Then 
     Range("A14:CE" & lastRow).Sort key1:=Range(Cells(14, Col), Cells(lastRow, Col)), 
     _Order1:=xlDescending, Header:=xlNo, key2:=Range("C14:C" & lastRow), 
     _Order2:=xlAscending, Header:=xlNo 
    End If 
Unload UserForm1 
End If 
End Sub 
0

變量AscendingOptionDescendingOption都未初始化,所以設置爲false。您需要將其中一個值更改爲TRUE進行排序。但是,在當前的代碼中,如果兩者都是TRUE,那麼您將對它進行兩次排序 - 首先是上升,然後是下降。你可以通過一個變量減少代碼爲:

If AscendingOption Then 
     Range("A14:CB" & lastRow).Sort key1:=Range(Col & "14:" & Col & lastRow), Order1:=xlAscending, Header:=xlNo, key2:=Range("C14:C" & lastRow), Order2:=xlAscending, Header:=xlNo 
    Else 
     Range("A14:CB" & lastRow).Sort key1:=Range(Col & "14", Col & lastRow), Order1:=xlDescending, key2:=Range("C14:C" & lastRow), Order2:=xlAscending 
    End If 

如果AscendingOption是真實的,它在排序中升序排列,否則降。

+0

我很抱歉,我忘了提及AscendingOption默認爲True,而另一個是False(請參閱編輯) –

+0

您能打印'AscendingOption'的值,通過' debug.print AscendingOption'到立即窗口或通過'msgbox AscendingOption'?因爲我檢查的其他人應該可以正常工作。因爲也許值不是從用戶表單提供給代碼? – Rufus