首页 > 解决方案 > 有什么方法可以将字符串附加到数组?

问题描述

如何将这些字符串附加到数组中?
我想附加的字符串

我正在尝试查看水果列表,并将当前不在数组中的任何水果添加到其中。(看到 apple 和 orange 不在数组中,因此添加它。然后看到以下苹果在数组中,因此忽略它并继续添加柠檬。)

Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = stringToBeFound Then
            IsInArray = True
            Exit Function
        End If
    Next i
    IsInArray = False

End Function


Public Sub Create_INDIVIDUAL_TABLES()

Dim tArray As String
Dim t1 As Integer
Dim t2 As Integer
Dim i As Integer

tArray = Array()
t1 = 3
t2 = 3
i = 0

Do While Cells(t1, "A").Value <> ""

    If IsInArray(Cells(t1, "B"), tArray) Then
        t1 = t1 + 1
    Else
        tArray(i) = Cells(t1, "B")
        i = i + 1
        t1 = t1 + 1
    End If
Loop

标签: arraysvbastring

解决方案


您可以通过使用 Redim Preserve 并更改其他一些内容来调整您的原始代码来执行此操作。

Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
Dim idx As Long

    For idx = LBound(arr) To UBound(arr)
        If arr(idx) = stringToBeFound Then
            IsInArray = True
            Exit Function
        End If
    Next idx

End Function


Public Sub Create_INDIVIDUAL_TABLES()
Dim tArray() As String
Dim cnt As Long
Dim t1 As Long

    ReDim tArray(1 To 1)
    t1 = 3
    cnt = 1
    tArray(cnt) = Cells(t1, "B")

    Do
        
        If Not IsInArray(Cells(t1, "B"), tArray) Then
            cnt = cnt + 1
            ReDim Preserve tArray(1 To cnt)
            tArray(cnt) = Cells(t1, "B")
        End If
        t1 = t1 + 1
    Loop Until Cells(t1, "A").Value = ""
    
End Sub

但是,如果您尝试从列表中获取唯一项目,您应该真正考虑使用collectionsdictionaries


推荐阅读