从 VBA 中的字符串中删除重复值 [英] Removing Duplicate values from a string in VBA

查看:111
本文介绍了从 VBA 中的字符串中删除重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 VBA 中,如果我有一串数字让我们说(1,2,3,4,5,2,2"),我怎样才能删除重复的值,只留下第一个实例,所以字符串说(1,2,3,4,5").

In VBA if I have a string of numbers lets say ("1,2,3,4,5,2,2"), how can I remove the duplicate values and only leave the first instance so the string says ("1,2,3,4,5").

推荐答案

如您所描述的,这是一个可用于对字符串进行重复数据删除的函数.请注意,这不会对删除的字符串进行排序,因此如果您的字符串类似于4,2,5,1,3,2,2",则结果将是4,2,5,1,3".您没有指定需要对其进行排序,因此我没有包含该功能.请注意,如果未指定,该函数使用 , 作为默认分隔符,但您可以选择指定分隔符.

Here is a function you can use to dedupe a string as you've described. Note that this won't sort the deduped string, so if yours was something like "4,2,5,1,3,2,2" the result would be "4,2,5,1,3". You didn't specify you needed it sorted, so I didn't include that functionality. Note that the function uses , as the default delimiter if not specified, but you can specify a delimiter if you choose.

Function DeDupeString(ByVal sInput As String, Optional ByVal sDelimiter As String = ",") As String

    Dim varSection As Variant
    Dim sTemp As String

    For Each varSection In Split(sInput, sDelimiter)
        If InStr(1, sDelimiter & sTemp & sDelimiter, sDelimiter & varSection & sDelimiter, vbTextCompare) = 0 Then
            sTemp = sTemp & sDelimiter & varSection
        End If
    Next varSection

    DeDupeString = Mid(sTemp, Len(sDelimiter) + 1)

End Function

这里有一些你会如何称呼它的例子:

Here's some examples of how you would call it:

Sub tgr()

    MsgBox DeDupeString("1,2,3,4,5,2,2")    '--> "1,2,3,4,5"

    Dim myString As String
    myString = DeDupeString("4-2-5-1-3-2-2", "-")
    MsgBox myString     '--> "4-2-5-1-3"

End Sub

这篇关于从 VBA 中的字符串中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆