我正在尝试按照第一列中的内容对x行进行排序。它必须是x行数,因为需要订购帽子的数量可以改变。
问题是行不是连续的,并且所有行都不需要与所有其他行一起排序。有些行只需要自己订购。
我已设法订购遇到的第一部分行,但在尝试使用循环继续对其余部分进行排序时,我的代码不会失败,但不会对其余行进行排序。
Private Sub CommandButton1_Click()
Dim startCond As Boolean
Dim stopCond As Boolean
Dim counter As Integer
Dim stopCount As Integer
stopCount = 1
startCond = False
stopCond = False
counter = 2
Dim neededRange As Range
Dim startIndex As Integer
Dim endIndex As Integer
For stopCount = 1 To 4
Do
If InStr(1, Cells(counter, 2).Value, "Start", 1) = 0 Then
counter = counter + 1
Else
startIndex = counter + 1
startCond = True
End If
Loop Until startCond = True
Do
If InStr(1, Cells(counter, 2).Value, "End", 1) = 0 Then
counter = counter + 1
Else
endIndex = counter - 1
stopCond = True
End If
Loop Until stopCond = True
Set neededRange = Sheet1.Range(Sheet1.Cells(startIndex, 1), Sheet1.Cells(endIndex, 1))
Rows(startIndex & ":" & endIndex).Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A" & startIndex), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A" & startIndex & ":CP" & endIndex)
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next stopCount
End Sub
https://www.dropbox.com/s/ascujl1lhk859bl/Eg%20for%20Excel.pdf
上面的链接显示了我想要排序的图片。
非常感谢任何帮助。
提前致谢。
答案 0 :(得分:0)
有几件事: - 你应该在你的do循环中应该使用的列索引应该是1而不是2 - 任何时候单元格被合并,它是结果范围中最左边/最顶部位置的单元格,它将保存分配给它的任何值 - 你应该重新初始化你的StartCond&在每次出现循环之前,StopCond变量为False
代码可以完善,但仅此一项就可以解决问题 - 或者反馈任何进一步的问题
Do
If InStr(1, Cells(counter, 1).Value, "Start", 1) = 0 Then
counter = counter + 1
Else
startIndex = counter + 1
startCond = True
End If
Loop Until startCond = True
startCond = False
Do
If InStr(1, Cells(counter, 1).Value, "End", 1) = 0 Then
counter = counter + 1
Else
endIndex = counter - 1
stopCond = True
End If
Loop Until stopCond = True
stopCond = False