vba - 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
解决方案
您应该会收到运行时错误 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()
它返回的是数组的实际长度,在您的情况下为三,因此它永远不会搜索到数组之外。
推荐阅读
- android - 应用程序模块也可以用作库模块吗?
- c# - 使用 Entity Framework Core 将数据存储和检索为 JSON 字符串?
- amazon-web-services - AWS CDK:将数据库实例分配给集群
- google-apps-script - 直接从 Sheets 将脚本部署为 Webapp
- swift - 将字符串转换为货币数字格式,带、不带或带 0 个小数位
- sql - 根据唯一条件在 HIVE 中创建新表选择记录
- python - 如何过滤给定时间范围的数据框?
- php - Symfony 5 登录表单操作返回无效的 CSRF 令牌
- javascript - 我可以将 google 地方自动填充功能限制在城市、城镇和社区吗?
- docker - 为什么我无法访问这个 helm chart 定义的应用程序?(在 Minikube 中)