首页 > 解决方案 > VBA:循环丢失变量值

问题描述

我在 VBA 中的循环有一个奇怪的问题,因为它似乎正在丢失我的变量的值。任何想法为什么?如果我删除循环,debug.print 显示“test”,否则它是空的(除非我在循环内打印“dupa”的值)......看起来很奇怪。

Function carbon_copy(indeks As String) As String

Dim emails(1 To 3) As String
Dim i As Integer
Dim dupa As String

emails(1) = "abc@wp.pl"
emails(2) = "pabc@wp.pl"
emails(3) = "rabc@wp.pl"

i = 1
dupa = "test"

Do While emails(i) <> ""

    If i = indeks Then
         GoTo NextIteration
    End If

    dupa = dupa & ";" & emails(i)


    NextIteration:
    i = i + 1

Loop

Debug.Print dupa

carbon_copy = dupa

End Function

标签: vbaloopsvariables

解决方案


您应该会收到运行时错误 9,因为i在您遍历 emails 字符串数组后,您的索引将为 4。一旦它尝试比较 的值,emails(4)""就会产生“超出范围的索引”,因为您已将 Array 定义为只有 3 个元素长。

为了澄清一下,试试这个示例代码,它应该会产生同样的错误:

Function littleTest()
    Dim teststr(1 To 3) As String
    Dim i As Integer

    teststr(1) = "abc"
    teststr(2) = "def"
    teststr(3) = "ghi"

    i = 1

    Do While teststr(i) <> ""
        Debug.Print "i do it for the " & i & " time!"
        i = i + 1
    Loop

End Function

您自己已经找到了解决方案,因为UBound()它返回的是数组的实际长度,在您的情况下为三,因此它永远不会搜索到数组之外。


推荐阅读