2016-12-15 72 views
1

當我不知道數組的大小時,如何將字段名稱添加到數組中?在我下面的兩個函數中,我能夠填充表沒有問題,但是當我嘗試創建數組時,它只會打印表中的第一條記錄。我必須做什麼才能創建具有所有值的數組?創建一維動態數組

Function PopulateTable() 
Set rs1 = db.OpenRecordset("MasterList") 
For Each fld In rs1.Fields 
    StrSQL = "INSERT INTO HoldTable (FieldList) VALUES ('" & fld.Name & "');" 
    DoCmd.SetWarnings False 
    DoCmd.RunSQL StrSQL 
Next 
'Create array of all fld.Name Values 
PopulateArray 
End Function 

Function PopulateArray() 
Dim rstData As DAO.Recordset 
Dim v   As Variant 
Dim cn   As Variant 

Set rstData = CurrentDb.OpenRecordset("select fieldlist from HoldTable") 
v = rstData.GetRows(rstData.RecordCount) 
For Each cn In v 
    Debug.Print CStr(cn) 
Next 

End Function 
+1

從[文檔](https://msdn.microsoft.com/en環-us/library/office/ff194427.aspx)(我強調),「GetRows返回***二維***數組。」 – Comintern

回答

1

您應該使用ADODB.Connection和OpenSchema方法來獲得字段名稱的列表:List database objects (tables, columns..) using ADO/ADOX

你需要使用rstData.MoveLast,然後rstData.MoveFirst得到準確RecordCount

Function PopulateTable() 
    Set rs1 = CurrentDb.OpenRecordset("MasterList") 
    For Each fld In rs1.Fields 
     StrSQL = "INSERT INTO HoldTable (FieldList) VALUES ('" & fld.Name & "');" 
     'Create array of all fld.Name Values 
     DoCmd.SetWarnings False 
     DoCmd.RunSQL StrSQL 
    Next 
    PopulateArray 
End Function 

Function PopulateArray() 
    Dim rstData As DAO.Recordset 
    Dim v As Variant 
    Dim cn As Variant 

    Set rstData = CurrentDb.OpenRecordset("Select fieldlist FROM HoldTable") 
    rstData.MoveLast 
    rstData.MoveFirst 
    v = rstData.GetRows(rstData.RecordCount) 
    For Each cn In v 
     Debug.Print CStr(cn) 
    Next 

End Function 
+0

非常好,那是我需要的。感謝您的幫助。 –

+0

@StarsFlyFreeFromCozyNights感謝您接受我的答案..again。 :) – 2016-12-15 02:20:58

0

可以定義一個「正常」的變量,並分配一個空數組給它:

Dim v : v = Array() 

然後你可以REDIM它:

ReDim Preserve v(rstData.RecordCount) 
+0

如果我在我的Debug.Print語句下添加ReDim Preserve語句,我得到'該數組已被修復或暫時鎖定'錯誤 –

+0

,但是您是否也將v的聲明更改爲Dim v()或Dim v: v = Array()? –

1

這是我會怎樣創建動態數組。 我將通過數據和每次迭代內遞增陣列的大小,然後將該值設置爲新遞增的陣列

Dim arraySize as Integer 
Dim dynArray() As string 
arraySize = -1 ' set to -1 so when you first increment the size by one it will start at index 0 

' Iterating through rstData variable 
for each fld in rstData.fields 
    arraySize = arraySize + 1 
    redim preserve dynArray(arraySize) as String 
    dynArray(sz) = fld ' not sure if can set it to fld directly or if need to access the value property of fld 
next 
' End of iterating through