2013-11-01 50 views
2

我試圖插入一個名稱和它的值轉換成二維數組:REDIM與二維數組

____________ 
| name| value| index 0 
|name1|value1| index 1 
|name2|value2| index 2 ... 
     . 
     . 
     . 

我迄今所做的:

Function ParseCSV(ByVal FileName As String) 
Dim FS   'As Scripting.FileSystemObject 
Dim Txt   'As Scripting.TextStream 
Dim CSVLine 
Dim arrayOfElements 
Dim nbErrors As Integer 
Dim namesNotInDb() As String 
Dim element As Variant 
Dim errorMsg As String 
Dim namesAgeMatrix() As String 
Dim nbrAges As Integer 


Set FS = CreateObject("Scripting.FileSystemObject") 
Set Txt = FS.OpenTextFile(FileName, 1, False) 
nbrAges = 0 
Do While Not Txt.AtEndOfStream 
    If nbrAges = 0 Then ReDim namesAgeMatrix(0, 1) Else ReDim Preserve namesAgeMatrix(nbrAges, 1) 
    CSVLine = Txt.ReadLine 
    arrayOfElements = Split(CSVLine, ",") 
    namesAgeMatrix(nbrAges, 0) = arrayOfElements(0) 
    If arrayOfElements(1) = "N/A" Then 
     nbErrors = nbErrors + 1 
     ReDim Preserve snamesNotInDb(nbErrors) 
     namesNotInDb(nbErrors) = arrayOfElements(0) 
     instrumentPriceMatrix(nbrInstruments, 1) = 0 
    Else 
     namesAgeMatrix(nbrAges, 1) = arrayOfElements(1) 
    End If 
    nbrAges = nbrAges + 1 
Loop 
Txt.Close 
If nbErrors > 0 Then 'displaying error/success message 
    errorMsg = "" 
    For Each name In namesNotInDb 
     errorMsg = errorMsg & name & " " 
    Next 
    MsgBox "Warning : " & errorMsg & "have no feed in DB. Name set by default to John.", vbExclamation 
Else 
    MsgBox "Importation success!", vbOKOnly 
End If 
ParseCSV = namesAgeMatrix 
End Function 

我得到的錯誤是: Subscription our of range以下:

Else ReDim namesAgeMatrix(nbrAges, 1) 

我怎樣才能REDIM我的數組的正確方法?

在此先感謝。

+0

你檢查'nbrNames'的價值? – sam092

+0

它的值是1. – Pol0nium

+0

CSVLine定義在哪裏? – stobin

回答

2

您只能在VBA中「Redim」多維數組的最後一個元素。

使用數組一樣的格式...

Variable(Row, Column) 

實際上是相對於你的工藝落後,如果這個想法是要添加「行」。

你需要你的陣列結構反轉的下面......

Variable(Column, Row) 

在此格式下,你可以在開始定義的信息「列」的號碼,然後一遍遍REDIM行。

​​

這需要一些時間來適應,因爲Excel和Office類型系統,甚至你的自然傾向是有它的結構爲「行,列」