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发布于 2018-11-28 14:07:12
你在数组边界之外建立索引。给定数组,条件Do While emails(i) <> ""始终为真,因此这在emails(4)上失败。只需测试数组边界并对其进行循环:
For i = LBound(emails) To UBound(emails)
If emails(i) <> "" And i = indeks Then
dupa = dupa & ";" & emails(i)
End If
Next发布于 2018-11-28 14:06:05
您应该得到一个运行时错误9,因为您的索引i将是4后,您通过您的电子邮件字符串数组。一旦它试图比较emails(4)和""的值,就应该生成“超出范围的索引”,因为您已经将数组定义为只有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,所以它将永远不会搜索到数组之外。
发布于 2018-11-28 14:04:09
实际上,我已经通过使用其他循环类型(I=1 To UBound(电子邮件),Next i)解决了这个问题,但是对于我来说,前一个循环为什么不能工作对我来说仍然很神秘.如果有人能解释的话,我会很感激的,因为我更喜欢理解事物,而不是感谢,只要正确地去做。
W。
https://stackoverflow.com/questions/53520979
复制相似问题