【问题标题】:Any way to append strings to Array?有什么方法可以将字符串附加到数组?
【发布时间】:2021-07-03 04:25:17
【问题描述】:

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

我正在尝试查看水果列表,并将当前不在数组中的所有水果添加到其中。 (看到 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

【问题讨论】:

    标签: arrays vba string


    【解决方案1】:

    您可以通过使用 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

    【讨论】:

    • 到目前为止,您的解决方案对我有用,非常感谢!我是编码新手,所以我会尽力分析你是如何处理它的!
    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 2017-01-30
    • 1970-01-01
    • 2019-01-02
    • 2011-01-18
    相关资源
    最近更新 更多