我有一个代码,它从定义的单元格返回所有匹配值的数字序列字符串。 插图如下:
COL A COL B COL C
Item No Data Unique Data
1 A A
2 A B
3 A
4 B
5 B
6 A
7 A
8 B
9 B
10 B
Cell D2 = Lookupsequence(C2,B2:B11,A2:A11)将返回1, 2, 3, 6, 7
Cell D3 = Lookupsequence(C3,B2:B11,A2:A11)将返回4, 5, 8, 9, 10
然而,我想要的结果是;
细胞D2 - > 1-3, 6-7
细胞D3 - > 4-5, 8-10
以下是我使用的功能代码:
Function Lookupsequence(Search_string As String, _
Search_in_col As Range, Return_val_col As Range)
Dim i As Long
Dim result As String
For i = 1 To Search_in_col.Count
If Search_in_col.Cells(i, 1) = Search_string Then
result = result & ", " & Return_val_col.Cells(i, 1).Value
End If
Next
Lookupsequence = Trim(result)
End Function
答案 0 :(得分:0)
试试这个:
Function Lookupsequence(Search_string As String, _
Search_in_col As Range, Return_val_col As Range)
Dim i As Long
Dim result As String
Dim initial As String
Dim separator As String
Dim preValue As Integer
Dim value As Integer
preValue = -1
separator = ""
For i = 1 To Search_in_col.Count
value = CInt(Return_val_col.Cells(i, 1).value)
If Search_in_col.Cells(i, 1) = Search_string Then
If value - 1 = preValue Then
result = initial & "-" & value
Else
result = result & separator & value
initial = result
separator = ","
End If
preValue = value
End If
Next
Lookupsequence = Trim(result)
End Function