bm1*_*563 5 excel vba excel-vba
我有一个包含50行逗号分隔数据的Excel电子表格。逗号分隔数据中包含的特征数量从下到上递增,即第50行(最后一行)始终具有最少的分隔符,而第1行(第一行)始终具有最多的分隔符。功能部件的数量随机增加,每个功能部件可以是唯一的或重复的。可以在每一行的字符串中添加多个或单个功能。将要素随机放置在前一行的逗号分隔字符串中,即可以将它们放置在上一行中字符串的中间,或者放置在上一字符串的开头或结尾。如果一行中添加了多个,则它们可能不会放在一起。例如:
1 fish,pig,cat,dog,fish,mouse,fish,cow
2 pig,cat,dog,fish,mouse,fish
3 pig,cat,dog,fish,mouse
4 pig,cat,dog,mouse
5 pig,cat,dog,mouse
6 cat,dog,mouse
7 cat,mouse
8 cat,mouse
9 cat
10
Run Code Online (Sandbox Code Playgroud)
我需要提取已添加到每行上以逗号分隔的字符串中的功能,最好使用UDF。上面示例的期望输出为:
1 fish,cow
2 fish
3 fish
4
5 pig
6 dog
7
8 mouse
9 cat
10
Run Code Online (Sandbox Code Playgroud)
使用UDF比较相邻行并提取相邻列的两行之间的唯一值时,我取得了一些成功(即,如果B4中的第4行和第5行使用了UDF,则B4将为空白;但是,如果UDF用于B3中的第3行和第4行,B3的值为“ fish”)。但是,这会导致问题,因为某些功能是重复的(请参见上例中的第1行和第2行)。当将重复项添加到字符串时,这导致UDF返回空值。
我在堆栈交换中发现的这些(非常细微调整的)UDF取得了最大的成功,特别是前者:
Function NotThere(BaseText As String, TestText As String) As String
Dim V As Variant, BaseWords() As String
NotThere = "" & TestText & ","
For Each V In Split(BaseText, ",")
NotThere = Replace(NotThere, V & ",", ",")
Next
NotThere = Mid(Application.Trim(NotThere), 3, Len(NotThere) - 0)
End Function
Run Code Online (Sandbox Code Playgroud)
和
Function Dups(R1 As String, R2 As String) As String
Dim nstr As String, R As Variant
For Each R In Split(R2, ",")
If InStr(R1, Trim(R)) = 0 Then
nstr = nstr & IIf(nstr = "", R, "," & R)
End If
Next R
Dups = nstr
End Function
Run Code Online (Sandbox Code Playgroud)
我还尝试了此处建议的方法:http : //www.ozgrid.com/VBA/array-differences.htm,但是不断出现#VALUE错误。
迭代两个数组并在发现重复项时将其删除。完成后返回剩下的内容:
Function newadd(rng1 As String, rng2 As String) As String
If rng1 = "" Then
newadd = rng2
Exit Function
End If
Dim spltStr1() As String
spltStr1 = Split(rng1, ",")
Dim spltstr2() As String
spltstr2 = Split(rng2, ",")
Dim i As Long, j As Long
Dim temp As String
For i = LBound(spltstr2) To UBound(spltstr2)
For j = LBound(spltStr1) To UBound(spltStr1)
If spltStr1(j) = spltstr2(i) Then
spltStr1(j) = ""
spltstr2(i) = ""
Exit For
End If
Next j
If spltstr2(i) <> "" Then
temp = temp & "," & spltstr2(i)
End If
Next i
newadd = Mid(temp, 2)
End Function
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |