Microsoft Visual Basic - Access 2016 - 运行时错误“9”:下标超出范围

问题描述 投票:1回答:1

我是VBA的新手,所以我对它有一个非常基本的了解,并且在运行以下代码时遇到问题:

Sub arrayData()
Dim custnames() As Variant
Dim num As Integer, dbs As Database, InsertRecord As String
Dim CustId As Integer, num1 As Integer
Dim CustName As String
Set dbs = CurrentDb()
CustId = 0
For num1 = 0 To 30000
CustId = CustId + 1
custnames = Array("Michael", "Larry", "Jeff", "Liam", "Gavin", "Ron", "Trevor", "Lester", "Leon", "Garry")



num = Int((30000 - 0 + 1) * Rnd + 0)
CustName = custnames(num)

InsertRecord = "insert into CUSTOMER (Cust_No, Cust_Name) values (" & "'" & CustId & "'" & "," & "'" & CustName & "'" & ")"

dbs.Execute InsertRecord
Debug.Print CustId; CustName

Next

End Sub

当我按下运行说“运行时错误'9':下标超出范围并且调试突出显示CustName = custnames(num)时弹出错误。此代码的目标是填写一个包含30,000条记录的表。

vba access
1个回答
0
投票

您正在创建1到30000之间的索引,但该数组只有10个元素。您希望生成范围内的随机整数,通常如下所示:

num = Int((UBound(custnames) - LBound(custnames) + 1) * Rnd + LBound(custnames))

因为你知道下界是0:

num = Int((UBound(custnames) + 1) * Rnd)

正如@Comintern指出的那样,您还应该在循环外部移动数组。

© www.soinside.com 2019 - 2024. All rights reserved.