If语句VBA中的字符串比较

时间:2013-12-05 23:08:46

标签: vba word-vba

我希望了解如何比较VBA中If语句中的字符串。

我想在if语句中使用字符串比较,以便从具有重复字符串的数组创建唯一字符串数组

Ex:[x,y,y,z,z,z] - > [X,Y,Z]

Dim A() As String = {"abc","abc","abc","def","def","ghi"}
Dim Alength As Long = Len(A)
Dim tempcounter As Integer = 0
Dim B As String()


For i = 1 To Alength

If i = 1 Then
    tempcounter = tempcounter + 1
    ReDim Preserve B(tempcounter) As String
    B(tempcounter) = A(i)


ElseIf i > 1 Then
    If A(i) <> A(i - 1) Then

        tempcounter = tempcounter + 1
        ReDim Preserve B(tempcounter) As String
        B(tempcounter) = A(i)
    End If
End If
Next

使用此代码,B返回A的副本。我希望B最终为(“abc”,“def”,“ghi”)

我尝试在if语句中使用字符串比较,例如: StrComp(A(i),A(i-1)),但我无法使其发挥作用。

我需要做些什么来使字符串比较函数我打算如何?

2 个答案:

答案 0 :(得分:0)

更快的方法是使用Dictionary对象。这是我的Unique方法。您将需要对Microsoft Scripting Runtime的引用:

' ------------------------------------------------------------------------------
'  Returns an array containing unique items in the source enumerable object
'  by using identity comparison built in to the Dictionary object. Preserves
'  all object types; also string "1" will not equal number 1
' ------------------------------------------------------------------------------
Public Function Unique(ByRef EnumerableObject)
    Dim oHash As New Dictionary
    Dim vItem
    For Each vItem In EnumerableObject
        oHash(vItem) = True
    Next
    Unique = oHash.Keys
End Function

答案 1 :(得分:0)

定义数组的方式存在一些问题。实际上,您的代码甚至不会在VBA中运行。我已编辑了您的代码,因此它将按照描述运行。

Sub CompareString()
    Dim A() As Variant
    Dim Alength As Long
    Dim B() As String
    Dim TempCounter As Integer
    Dim Flag As Boolean

    A = Array("abc", "abc", "abc", "def", "def", "ghi")
    TempCounter = 0
    ReDim B(0 To 0)

    'Loops through A
    For i = 0 To UBound(A) Step 1
        Flag = False

        'Loops through B
        For j = 0 To UBound(B) Step 1
            If A(i) = B(j) Then
                Flag = True
                Exit For
            End If
        Next j

        'If the element was not found in B it will be added
        If Flag = False Then
            ReDim Preserve B(0 To TempCounter)
            B(UBound(B)) = A(i)
            TempCounter = TempCounter + 1
        End If
    Next i
End Sub