我正在嘗試對之前設定的范圍進行排序,但它不起作用,而且我無法找到問題所在。因此,歡迎任何幫助
我的程式對特定作業表中的所有資料進行排序,然后根據條件設定范圍。
Sub References_Sort()
' Activate Worksheet
Dim ws As Worksheet
Set ws = Application.ThisWorkbook.Worksheets("Hoja2")
ws.Activate
'Set variables
Dim LastColumn, LastRow, FirstRow As Integer
Dim rngCom As Range
Dim i As Long
'Sort the rows based on the data in column E
ws.Columns("A:I").Sort _
key1:=Range("E2"), _
order1:=xlAscending, _
Header:=xlYes
'Find which is the last row and last column with data
LastColumn = Cells(1, Columns.Count).End(xlToLeft).Column
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
With ws
'Find first row with value=5 in column E
FirstRow = .Range("E:E").Find(What:=5, After:=.Range("E1")).Row
' Set range which includes data with value=5 in column E
Set rngCom = .Range(Cells(FirstRow, "A"), Cells(LastRow, LastColumn))
'Sort set range based on the data in column B
rngCom.Sort _
key1:=Range("B2"), _
order1:=xlAscending, _
Header:=xlYes
End With
End Sub
uj5u.com熱心網友回復:
您的某些Range物件不合格。
像這樣限定它們(見評論):
Sub References_Sort()
' Activate Worksheet
Dim ws As Worksheet
Set ws = Application.ThisWorkbook.Worksheets("Hoja2")
ws.Activate
'Set variables
' Dimmed them as Long instead of 2 variants and 1 integer
Dim LastColumn As Long, LastRow As Long, FirstRow As Long
Dim rngCom As Range
Dim i As Long
'Sort the rows based on the data in column E
' (added ws. to the range object)
ws.Columns("A:I").Sort _
key1:=ws.Range("E2"), _
order1:=xlAscending, _
Header:=xlYes
'Find which is the last row and last column with data
' these cells references should probably be qualified too
' added ws. to them
LastColumn = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
With ws
'Find first row with value=5 in column E
FirstRow = .Range("E:E").Find(What:=5, After:=.Range("E1")).Row
' Set range which includes data with value=5 in column E
' fixed missing qualifications here too
Set rngCom = .Range(.Cells(FirstRow, "A"), .Cells(LastRow, LastColumn))
'Sort set range based on the data in column B
' (added a . to the Range object to qualify it using the with)
rngCom.Sort _
key1:=.Range("B2"), _
order1:=xlAscending, _
Header:=xlYes
End With
End Sub
僅作記錄,OP 希望對此進行更改(請參閱評論):
rngCom.Sort _
key1:=.Range("B1"), _
order1:=xlAscending, _
Header:=xlNo
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/314582.html
下一篇:MongoDB按計算欄位排序
