【问题标题】:How can I use a for each loop on an array?如何在数组上使用 for each 循环?
【发布时间】:2011-05-12 19:18:27
【问题描述】:

我有一个字符串数组:

Dim sArray(4) as String

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

for each element in sarray
  do_something(element)
next element

do_something 将字符串作为参数

将元素作为字符串传递时出错:

ByRef 参数不匹配

我应该将元素转换为字符串还是什么?

【问题讨论】:

  • 听起来你的 do_something 签名已经指定了 byref 但它应该是 byval 代替?

标签: excel vba


【解决方案1】:

元素需要是一个变体,所以你不能将它声明为一个字符串。你的函数应该接受一个变体,如果它是一个字符串,但只要你通过 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)

【讨论】:

  • 由于 sArray 是空的,这将什么都不做?!?!
  • @EdwardBlack - 他只给出了与讨论相关的代码 sn-ps。据推测,sArray 的尺寸标注和 For Each 循环之间的附加代码实际上会定义它。但如何定义对于这个问题并不重要。
【解决方案2】:

每个循环结构更多地是围绕集合对象设计的。 For..Each 循环需要一个变体类型或对象。由于您的“元素”变量被键入为变体,因此您的“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

【讨论】:

  • +一、LBound和UBound的使用很明确!!虽然另一种选择是使用 For Each 块..
  • lboundubound 在循环中需要索引 i 时很有用,并且与 foreach 相比可以是另一个用例。
【解决方案3】:

我使用 Fink 建议的计数器变量。如果您想要 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

【讨论】:

    【解决方案4】:

    这个简单的 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
    

    【讨论】:

      【解决方案5】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-11-12
        • 1970-01-01
        • 1970-01-01
        • 2013-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多