gpt4 book ai didi

excel - 从单元格中删除重复的字符串,但保留重复的最后一个实例

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

在 excel 上使用 VBA 从单元格中删除重复的字符串(整个单词),但保留重复项的最后一个实例。
例子

hello hi world hello => hi world hello
this is hello my hello world => this is my hello world
我最初是一名 python 开发人员,所以请原谅我在 VBA 中缺乏语法,我编辑了一段在线找到的代码,其逻辑如下:
'''
函数 RemoveDupeWordsEnd(text As String, Optional delimiter As String = "") As String
暗淡字典作为对象
暗淡 x,零件,尾字
Set dictionary = CreateObject("Scripting.Dictionary")
dictionary.CompareMode = vbTextCompare
For Each x In Split(text, delimiter)
part = Trim(x)

If part <> "" And Not dictionary.exists(part) Then
dictionary.Add part, Nothing
End If

'' COMMENT
'' if the word exists in dictionary remove previous instance and add the latest instance
If part <> "" And dictionary.exists(part) Then
dictionary.Del part, Nothing
endword = part
dictionary.Add endword, Nothing
End If


Next

If dictionary.Count > 0 Then
RemoveDupeWordsEnd = Join(dictionary.keys, delimiter)
Else
RemoveDupeWordsEnd = ""
End If

Set dictionary = Nothing
结束功能
'''
感谢所有帮助和指导,将不胜感激

最佳答案

保留匹配子串的最后一次出现

Option Explicit

Function RemoveDupeWordsEnd( _
ByVal DupeString As String, _
Optional ByVal Delimiter As String = " ") _
As String

Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare

Dim Item As Variant
Dim Word As String

For Each Item In Split(DupeString, Delimiter)
Word = Trim(Item)
If Len(Word) > 0 Then
If dict.Exists(Word) Then
dict.Remove Word
End If
dict(Word) = Empty ' the same as 'dict.Add Word, Empty'
End If
Next Item

If dict.Count > 0 Then RemoveDupeWordsEnd = Join(dict.Keys, Delimiter)

End Function

关于excel - 从单元格中删除重复的字符串,但保留重复的最后一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71175666/

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