2017-04-25 69 views
0

一直在試圖插入一條街,郊區和郵政編碼到表中,但不斷收到運行時錯誤「13」類型不匹配的MS Access VBA陣列

運行時錯誤「13」 類型不匹配

下面是代碼:

應該持有陣列需要聲明爲Variant,而不是作爲字符串
Sub arrayData() 

Dim CustomerNames() As Variant 
Dim num As Long, dbs As Database, InsertReocrd As String 
Dim CustomerID As Long, num1 As Long 
Dim CustomerName As String 
Dim Street As String, Suburb As String, Postcode As Integer 

Set dbs = CurrentDb() 
CustomerID = 0 
For num1 = 0 To 50000 
CustomerID = CustomerID + 1 
CustomerNames = Array(...) 

Street = Array("Short", "Lygon", "Flinders", "Elizabeth", "King") //ERROR OCURRS HERE 

Suburb = Array("Sandringham", "Brighton", "St Kilda", "Melbourne", "Carlton") //ERROR OCURRS HERE 

Postcode = Array("3165", "3298", "3145", "3144", "3000") //ERROR OCURRS HERE 

num = Int((250 - 0 + 1) * Rnd + 0) 
CustomerName = CustomerNames(num) 
InsertRecord = "INSERT INTO CUSTOMER (CustomerID , CustomerName, StreetName, Suburb) VALUES (" & "'" & CustomerID & "'" & "," _ 
                    & "'" & CustomerName & "'" & "'" & StreetName & "'" & ")" 

dbs.Execute InsertRecord 
Debug.Print CustomerID, CustomerName, Street, Suburb 
Next 

End Sub 

回答

1

變量。

所以:

Dim Street As Variant, Suburb As Variant, Postcode As Variant 

注意,INSERT語句中缺少郊區的價值。

使用DAO.Recordset.AddNew等可能會更快,更好的可讀性。

+0

你可以告訴我你是什麼意思,因爲我拼寫時拼寫INSERT語句。 – TimboMan

+0

下面是一個記錄集的例子:http://stackoverflow.com/a/36997654/3820271 – Andre

0

由於shown yesterday,簡化拼接,你還需要和客戶ID和環陣列,以及:(?)

For n = 1 To 5  
    InsertRecord = "INSERT INTO CUSTOMER (CustomerID , CustomerName, StreetName, Suburb) VALUES (" & CustomerID(n) & ",'" & CustomerName(n) & "','" & StreetName(n) & "','" & Suburb(n) & "')" 

如果你真的想插入50000個客戶這種方式(你止跌」 t),遵循André的建議並使用DAO。

+0

我不斷收到'Expected array'是什麼原因造成的?當我爲此產生隨機數字時。 – TimboMan

+0

在我的代碼中,CustomerID也是一個數組。所以修改你的代碼來採用。 – Gustav

相關問題