我之前从未发布过论坛,所以如果我打破任何论坛礼仪,我会道歉。我已尝试在此论坛和一般互联网搜索中搜索此答案,但无法找到我正在寻找的内容。
我有两列数字,格式为# - #。基本上,第一个数字是章节号,第二个是章节号。如果在两列中,这些部分都是连续的范围,我需要它来组合它们。例如:
2-16 | 2-31
2-17 | 2-32
2-18 | 2-33
2-30 | 2-55
会变成:
2-16--2-18 | 2-31--2-33
2-30 | 2-55
我很抱歉格式化。我尝试用连字符分隔并编写一次检查所有四行的代码,但我似乎无法弄清楚如何检查这些部分以查找它们何时停止连续。任何帮助表示赞赏!
答案 0 :(得分:0)
我认为这是一个有趣的问题所以我自己尝试了一些东西。我只是一个新的学习者,我不知道我的代码是否足够有效,但我测试了它并且它有效。
Private Sub Combine()
Dim i, j, m, n As Integer
Dim LookStart, SvaeStart As Range
'Assume the data stored in column A, Cells A2:A9
'Put the results in Column B,starting with cell B2
Set LookStart = Range("A2")
Set SaveStart = Range("B2")
i = 0
j = FindEnd(LookStart)
m = 0
Do
n = FindNext(LookStart.Offset(m, 0))
SaveStart.Offset(i, 0).Value = LookStart.Offset(m, 0).Value
If n <> 0 Then
SaveStart.Offset(i, 0).Value = SaveStart.Offset(i, 0).Value & _
" -- " & LookStart.Offset(m + n, 0).Value
End If
m = m + n + 1
i = i + 1
Loop While m <= j
End Sub
Private Function FindEnd(ByVal start As Range) As Integer
FindEnd = Range("A1").Offset(Cells.Rows.Count - 1, _
start.Column - 1).End(xlUp).Row - start.Row
End Function
Private Function FindNext(ByVal start As Range) As Integer
Dim i, j, flag, CurrentNum, LastNum As Integer
Dim CurrentText As String
i = 0
j = FindEnd(start)
flag = 0
Do
CurrentText = start.Offset(i, 0).Text
If i <> 0 Then
If LastNum + 1 <> Left(CurrentText, Application.WorksheetFunction.Find("-", _
CurrentText) - 1) * 100 + Right(CurrentText, 2) Then flag = 1
End If
LastNum = Left(CurrentText, Application.WorksheetFunction.Find("-", _
CurrentText) - 1) * 100 + Right(CurrentText, 2)
i = i + 1
Loop While flag = 0 And i <= j
If flag = 0 Then FindNext = i - 1
If flag = 1 Then FindNext = i - 2
End Function
结果如下:
A栏| B栏
2-16 | 2-16 - 2-18
2-17 | 2-30
2-18 | 2-32 - 2-34
2-30 | 2-56 - 2-58
2-32 | 2-60
2-33
2-34
2-56
2-57
2-58
2-60
有没有人可以帮我改进我的代码?真的非常感谢!
希望这可以帮到你!
答案 1 :(得分:0)
假设您拥有指定范围内的数据 - 在本例中为“ChaptersAndSections”..
For Each rCol In Range("ChaptersAndSections").Columns
With Range(rCol.Address)
For r = 1 To .Rows.Count
sValue = .Rows(r).Value
sValue2 = .Rows(r).Value
If Not r + 1 > .Rows.Count Then
Do While CInt(Mid(.Rows(r + 1).Value, InStrRev(.Rows(r + 1).Value, _
"-") + 1)) = CInt(Mid(sValue2, InStrRev(sValue, "-") + 1)) + 1
sValue2 = .Rows(r + 1).Value
.Rows(r + 1).Delete shift:=xlUp
Loop
End If
If sValue <> sValue2 Then .Rows(r).Value = sValue & "--" & sValue2
Next r
End With
Next rCol
应该不言而喻,但请务必在工作表的副本上进行测试,因为我只使用您在示例中提供的小数据集对其进行了测试。