简体   繁体   English

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

[英]How can I use a for each loop on an array?

I have an array of Strings:我有一个字符串数组:

Dim sArray(4) as String

I am going through each String in the array:我正在遍历数组中的每个字符串:

for each element in sarray
  do_something(element)
next element

do_something takes a string as a parameter do_something接受一个字符串作为参数

I am getting an error passing the element as a String:将元素作为字符串传递时出现错误:

ByRef Argument Mismatch ByRef 参数不匹配

Should I be converting the element to a String or something?我应该将元素转换为字符串还是什么?

Element needs to be a variant, so you can't declare it as a string.元素需要是一个变体,所以你不能将它声明为一个字符串。 Your function should accept a variant if it is a string though as long as you pass it ByVal.如果你的函数是一个字符串,你的函数应该接受一个变体,只要你通过 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

The other option is to convert the variant to a string before passing it.另一种选择是在传递之前将变体转换为字符串。

  do_something CStr(element)

A for each loop structure is more designed around the collection object. for each循环结构更多的是围绕集合对象设计的。 A For..Each loop requires a variant type or object. For..Each 循环需要变体类型或对象。 Since your "element" variable is being typed as a variant your "do_something" function will need to accept a variant type, or you can modify your loop to something like this:由于您的“元素”变量被输入为变体,因此您的“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

I use the counter variable like Fink suggests.我像 Fink 建议的那样使用计数器变量。 If you want For Each and to pass ByRef (which can be more efficient for long strings) you have to cast your element as a string using CStr如果你想要 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

what about this simple inArray function:这个简单的 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

If alternatives are acceptable for this case, I would rather suggest UBound:如果这种情况可以接受替代方案,我宁愿建议 UBound:

For i = 1 to UBound(nameofthearray)
   your code here
next i

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM