我有一张工作表,其中有第4行中各列的标题。我有一个代码,当我双击第4行中的某个单元格时,它将按该单元格对数据进行排序。我现在遇到的问题是在B列中,单元格与下面的行合并。因此,例如第4行和第5行已合并,第6行和第7行等。由于这些合并的单元格,我拥有的代码将不再让我排序。有人可以帮忙吗?
这是我正在使用的代码
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
lr = Cells(Rows.Count, "B").End(xlUp).row
lc = Cells(4, Columns.Count).End(xlToLeft).Column
If Target.row = 4 And Target.Column <= lc Then Range(Cells(4, "B"), Cells(lr, lc)).Sort Key1:=Cells(4, Target.Column), Header:=xlYes 'Order1:=xlDescending
End Sub
的图片
答案 0 :(得分:0)
尝试
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim lc As Integer
lc = Cells(4, Columns.Count).End(xlToLeft).Column
If Target.Row = 4 And Target.Column <= lc Then
sortdescent Target.Column - 1, lc
End If
End Sub
模块代码
Sub sortdescent(x As Integer, col As Integer)
Dim vDB
Dim strTemp()
Dim r As Integer, c As Integer, i As Integer, j As Integer
Dim m As Integer
ReDim strTemp(1 To 2, 1 To col)
vDB = Range("b5", Cells(Range("c" & Rows.Count).End(xlUp).Row, col))
r = UBound(vDB, 1)
c = UBound(vDB, 2)
For i = 1 To r Step 2
For j = 1 To r Step 2
'If vDB(j, x) > vDB(i, x) Then 'Ascent
If vDB(j, x) < vDB(i, x) Then 'Descent
For m = 1 To c
strTemp(1, m) = vDB(i, m)
strTemp(2, m) = vDB(i + 1, m)
vDB(i, m) = vDB(j, m)
vDB(i + 1, m) = vDB(j + 1, m)
vDB(j, m) = strTemp(1, m)
vDB(j + 1, m) = strTemp(2, m)
Next
End If
Next j
Next i
Range("b5").Resize(r, c) = vDB
End Sub