[算表] vba 篩選排序請教大神哪裡寫錯

作者: mini178 (mini178)   2023-09-16 22:42:25
軟體:excel
版本:office365
目的:透過vba進行篩選投本比1日後針對J欄(投本比1日(%))進行排序由大到小
因為中間想要保持空白列
所以想法是找到投本比1日的第一列的上一列去篩選
再針對J欄(投本比1日(%))排序由大到小
有用過chtgpt修改但還是不成功
沒顯示錯誤但不會排序
請問大神是哪裡錯誤
資料:https://imgur.com/W6XFrFy
Sub 篩選和排序()
Dim ws As Worksheet
Dim lastRow As Long
Dim filterRowStart As Long
Dim filterRowEnd As Long
' 定義工作表
Set ws = ThisWorkbook.Sheets("20230918盤前")
' 確定最後一行
lastRow = ws.Cells(ws.rows.Count, "A").End(xlUp).row
' 找到第一個出現"投本比1日"的上一列
For filterRowStart = 2 To lastRow
If ws.Cells(filterRowStart, 1).Value = "投本比1日" Then
Exit For
End If
Next filterRowStart
' 找到最後一個出現"投本比1日"的列
For filterRowEnd = lastRow To 2 Step -1
If ws.Cells(filterRowEnd, 1).Value = "投本比1日" Then
Exit For
End If
Next filterRowEnd
' 如果找到"投本比1日",則應用AutoFilter
If filterRowStart <= lastRow And filterRowEnd >= filterRowStart Then
' 篩選範圍從第一個出現"投本比1日"的上一列到最後一個出現"投本比1日"的列
ws.rows(filterRowStart - 1 & ":" & filterRowEnd).AutoFilter Field:=1,
Criteria1:="投本比1日"
' 排序投本比1日%
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add Key:=ws.Range("J" & filterRowStart - 1 & ":J"
& filterRowEnd), _
SortOn:=xlSortOnValues, Order:=xlDescending,
DataOption:=xlSortNormal
With ws.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
' 關閉篩選
ws.AutoFilterMode = False
End If
End Sub

Links booklink

Contact Us: admin [ a t ] ucptt.com