gpt4 book ai didi

vba - 识别逗号分隔字符串的新添加内容

转载 作者:行者123 更新时间:2023-12-02 07:24:13 24 4
gpt4 key购买 nike

我有一个 Excel 电子表格,其中包含 50 行逗号分隔的数据。逗号分隔数据中包含的特征数量从下到上增加,即第 50 行(最后一行)始终具有最少的分隔符,而第 1 行(第一个row) 始终具有最多的分隔符。特征的数量随机增加,每个特征可以是唯一的,也可以是重复的。可以将多个或单个特征添加到每行的字符串中。这些特征被随机放置到前一行的逗号分隔字符串中,即它们可以放置到前一行字符串的中间,或者前一个字符串的开头或结尾。如果一行中添加了多个,则它们可能不会放置在一起。例如:

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

我需要提取已添加到每行逗号分隔字符串中的特征,最好使用 UDF。上述示例所需的输出为:

1  fish,cow
2 fish
3 fish
4
5 pig
6 dog
7
8 mouse
9 cat
10

我使用 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

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

我也尝试过这里建议的方法: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

enter image description here

关于vba - 识别逗号分隔字符串的新添加内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50360139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com