arrays - 有什么方法可以将字符串附加到数组?
问题描述
我正在尝试查看水果列表,并将当前不在数组中的任何水果添加到其中。(看到 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
解决方案
您可以通过使用 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
但是,如果您尝试从列表中获取唯一项目,您应该真正考虑使用collections或dictionaries。
推荐阅读
- java - PHP 上的 AJAX 请求示例?
- php - 服务器返回内容类型 application/x-httpd-php5 而不是 application/json
- java - 有谁知道如何在 Android Studio 中使用 Expression?
- asp.net - EF 手动将实体列表附加到父实体中
- php - 如何在 PHP 中为数字(千、十万、百万、十亿)添加逗号分隔符
- python - Python:查找本地平均时间(根据位置时区子午线的经度距离进行调整)
- mysql - 使用 Jest 进行数据驱动测试
- java - 如何在 spring-webflux WebFilter 中正确使用 slf4j MDC
- java - 我在尝试用 int 值填充堆栈数组时遇到 OutOfMemoryError
- authentication - 调用 HttpContext.SignInAsync 后用户退出 IdentityServer4