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

查看:488
本文介绍了从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天全站免登陆