通过VB在Microsoft Access中多记录插入

时间:2017-10-18 20:07:58

标签: vba ms-access

我在Access中创建了数据库并给出了数据类型"短文本。"

现在我试图通过Visual Basic提示记录到这个表中。我到目前为止编写了一个代码,但需要帮助来修复错误。我收到了编译错误:

  

当前范围内的重复声明

我无法弄清楚它是什么?

Option Compare Database

Sub arrayData()

Dim CustomerName() As Variant 
Dim num As Integer, dbs As Database, InsertRecord As String
Dim CustomerID As Long, num1 As Long, CustomerName As String

Set dbs = CurrentDb() 
CustomerID = 0
For num1 = 0 To 49999

CustomerID = CustomerID + 1
CustomerName = Array("Peter", "Mary")
CustomerAddress = Array("163 City Rd, SOUTHBANK", "65 Orange St, BENTLEIGH EAST")
CustomerPhoneAddress = Array("0416874963", "0478937534")
num = Int((200 - 0 + 1) * Rnd + 0)
CustomerName = CustomerName(num)
CustomerAddress = CustomerAddress(num)
CustomerPhoneNo = CustomerPhoneNo(num)
InsertRecord = "INSERT INTO Customers (CustomerID,CustomerName,CustomerAddress,CustomerPhoneNo) VALUES (" & "'" & CustomerID & "'" & "," & "'" & CustomerName & "'" & "," & "'" & CustomerAddress & "'" & "," & "'" & CustomerPhoneNo & "'" & ")"

dbs.Execute InsertRecord
Debug.Print CustomerID, CustomerName, CustomerAddress, CustomerPhoneNo

Next

End Sub

在这种情况下我该怎么办?任何帮助,将不胜感激。

1 个答案:

答案 0 :(得分:0)

您使用的语言是" Visual Basic for Applications" (VBA)。这种语言是面向行的。它表示一个语句必须适合一行,除非你使用一个行连续符(_),前面至少有一个空格。

Dim CustomerID As Long, num1 As Long, CustomerName As String, CustomerAddress _
    As String, CustomerPhoneNo As String

但我会将LongString变量放在不同的行上并写下:

Dim CustomerID As Long, num1 As Long
Dim CustomerName As String, CustomerAddress As String, CustomerPhoneNo As String

第二个语法错误在InsertRecord = "INSERT INTO ...语句中。同样的问题在这里看起来像这样:

    InsertRecord = "INSERT INTO CUSTOMERS (CustomerID,CustomerName," _
        & "CustomerAddress,CustomerPhoneNo) VALUES " _
        & "(" & "'" & CustomerID & "'" & "," & "'" & CustomerName & "'" & "," & "'" _
        & CustomerAddress & "'" & "," & "'" & CustomerPhoneNo & "'" & ")"

此外,- 0中的+ 0Int((200 - 0 + 1) * Rnd + 0)有什么用处。该表达式相当于Int(201 * Rnd)

编辑后,您似乎没有续行。

错误是:您有2个名为CustomerName的变量。变量名必须是唯一的:

Dim CustomerName() As Variant
Dim CustomerName As String

例如,将数组命名为CustomerNames

Dim CustomerNames() As Variant

你应该缩进你的代码。它使阅读更容易。

Sub arrayData()
    Dim CustomerName() As Variant
    ...
    CustomerID = 0
    For num1 = 0 To 10
        CustomerID = CustomerID + 1
        ...
        Debug.Print CustomerID, CustomerName, CustomerAddress, CustomerPhoneNo
    Next
End Sub