我是VBA的新手,所以我对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条记录的表。
答案 0 :(得分:0)
您要创建一个介于1到30000之间的索引,但是该数组只有10个元素。您想要生成一个范围内的随机整数,通常按以下步骤进行操作:
num = Int((UBound(custnames) - LBound(custnames) + 1) * Rnd + LBound(custnames))
因为您知道下限是0:
num = Int((UBound(custnames) + 1) * Rnd)
正如@Comintern所指出的,您还应该将数组创建移到循环之外。