VBA:循环丢失变量值

时间:2018-11-28 13:50:47

标签: vba loops variables

我在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

4 个答案:

答案 0 :(得分:2)

您应该收到运行时错误9,因为在遍历电子邮件的String数组后,索引i的值为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()返回数组的实际长度(在您的情况下为3)以来,您就已经找到了解决方案。

答案 1 :(得分:0)

实际上,我已经通过使用其他循环类型(对于i = 1到UBound(emails),下一个i)解决了该问题,但是为什么上一个循环不起作用对我来说还是很神秘的...如果任何人都可以解释,我会很感激,因为我更喜欢理解事物,而不是感谢他们正确地做它们。

W。

答案 2 :(得分:0)

您正在索引超出数组范围。给定数组,条件Do While emails(i) <> ""始终为true,因此在emails(4)上失败。只需测试数组范围并在其上循环即可:

For i = LBound(emails) To UBound(emails)
    If emails(i) <> "" And i = indeks Then
        dupa = dupa & ";" & emails(i)
    End If
Next

答案 3 :(得分:0)

这应该有效(注释中的解释):

Function carbon_copy(indeks As Long) As String
    Dim emails(1 To 3) As String
    Dim i As Long
    Dim dupa As String

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

    i = 1
    Do While emails(i) <> ""
        If i <> indeks Then dupa = dupa & ";" & emails(i) ' update 'dupa' if current index doesn't natch passed 'indeks'
        i = i + 1
        If i > UBound(emails, 1) Then Exit Do ' be sure to exit upon exceeding 'emails()' array size
    Loop

    carbon_copy = dupa
End Function