如何在数组上使用 for every 循环?

问题描述 投票:0回答:5

我有一个字符串数组:

Dim sArray(4) as String

我正在遍历数组中的每个字符串:

for each element in sarray
  do_something(element)
next element

do_something
采用字符串作为参数

我在将元素作为字符串传递时遇到错误:

ByRef 参数不匹配

我应该将元素转换为字符串还是其他东西吗?

excel vba
5个回答
129
投票

element
需要是一个变体,因此不能将其声明为字符串。如果它是一个字符串,你的函数应该接受一个变体,尽管只要你通过 ByVal 传递它。

Public Sub example()
    Dim sArray(4) As string
    Dim element As variant

    For Each element In sArray
        do_something element
    Next element
End Sub


Sub do_something(ByVal e As String)
    
End Sub

另一个选项是在传递变量之前将其转换为字符串。

  do_something CStr(element)

45
投票

foreach循环结构更多是围绕集合对象来设计的。 For..Each 循环需要变体类型或对象。由于您的“element”变量被输入为变体,因此您的“do_something”函数将需要接受变体类型,或者您可以将循环修改为如下所示:

Public Sub Example()

    Dim sArray(4) As String
    Dim i As Long

    For i = LBound(sArray) To UBound(sArray)
        do_something sArray(i)
    Next i

End Sub

8
投票

我像芬克建议的那样使用计数器变量。如果您想要 For Each 并传递 ByRef (这对于长字符串可能更有效),您必须使用 CStr

将元素转换为字符串
Sub Example()

    Dim vItm As Variant
    Dim aStrings(1 To 4) As String

    aStrings(1) = "one": aStrings(2) = "two": aStrings(3) = "three": aStrings(4) = "four"

    For Each vItm In aStrings
        do_something CStr(vItm)
    Next vItm

End Sub

Function do_something(ByRef sInput As String)

    Debug.Print sInput

End Function

5
投票

这个简单的 inArray 函数怎么样:

Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
    If element = stringToBeFound Then
        isInArray = True
        Exit Function
    End If
Next element
End Function

2
投票

如果这种情况下可以接受替代方案,我宁愿建议 UBound :

For i = 1 to UBound(nameofthearray)
   your code here
next i
© www.soinside.com 2019 - 2024. All rights reserved.