我需要在 MS Access 中創建一個 ArrayList,然后向其中添加記錄。我正在使用以下方法:
Dim orphaned As Object
Set orphaned = CreateObject("System.Collections.ArrayList")
不幸的是,這種方法需要安裝我想避免的 .NET 3.5。
我對 VBA 和 Access 相當缺乏經驗。有什么解決方法/替代方法嗎?
uj5u.com熱心網友回復:
哼,為什么不用VBA集合物件呢?它們速度快,而且易于使用。
Sub TestFun55()
Dim MyThings As New Collection
' add 5 things to above
Dim strThing As String
Dim i As Integer
For i = 1 To 5
Dim strKey As String
strKey = i * 10
strThing = "Thing - " & strKey
MyThings.Add strThing, strKey
Next i
' get one thing by "key" value (we have 10, 20, 30, 40, 50
Debug.Print "Get first thing thing by index (1) = " & MyThings(1)
Debug.Print "Get thing by 'key value '10' (string key) = " & MyThings("10")
End Sub
因此,您可以通過“索引”(從 1 開始)從集合中取出。
或者您可以通過“密鑰”獲取。現在對于字串,那么我傾向于使“鍵”和字串值相同。但是它們非常快速地通過字串查找/獲取值。
所以,上面的輸出是這樣的:
Get first thing thing by index (1) = Thing - 10
Get thing by 'key value '10' (string key) = Thing - 10
通常,如果您想要強型別的變數和簡單的智能感知?
好吧,出于某種原因,VBA 不支持型別定義。
所以,100% 分開——用這個創建一個“類”模塊:
' module = clsPerson
Option Compare Database
Option Explicit
Public FirstName As String
Public LastName As String
現在,我們可以這樣:
Sub TestFun56()
Dim MyThings As New Collection
' add 3 Person things to colleciton
Dim OnePerson As clsPerson
Dim strThing As String
Dim i As Integer
For i = 1 To 2
Set OnePerson = New clsPerson
OnePerson.FirstName = "First" & i
OnePerson.LastName = "Last" & i
Dim strKey As String
strKey = "First" & i ' we key list by FirstName
Debug.Print "key = " & strKey
MyThings.Add OnePerson, strKey
Next i
' now, check for first name of "First2" in list
On Error Resume Next ' failure to find generates error!!!
Dim strFind As String
Dim strResult As clsPerson
strFind = "First1"
Set strResult = MyThings(strFind)
If Err.Number = 0 Then
' got one!
Debug.Print strResult.FirstName
Debug.Print strResult.LastName
Else
Debug.Print "not found"
End If
' and of course we can referace/use by index
Debug.Print MyThings(1).FirstName
Debug.Print MyThings(1).LastName
End Sub
不管?我收藏很好。你也有
MyThings.Count - how many
MyThings(int index).
不幸的是,這里沒有辦法將字串“key”轉換為索引。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/508026.html