2014-02-27 88 views
3

我的任務:打開.csv文件的vbscript將數據讀入數組,使用該數據執行函數,然後將更新的數據返回給同一個文件。我相信我有其他的工作,除了我的功能從文件讀取數據。vbscript將csv讀入數組

我的問題:我嘗試使用此代碼時收到運行時錯誤。與腳本一樣,我得到一個錯誤:類型不匹配。我嘗試改變一些代碼並獲得不同的運行時錯誤。

這個代碼的幾個注意事項:

  1. 我希望它跳過csv文件這是永遠不會改變的標題的第一道防線。
  2. 總會有精確的12個字段。但是,行數是動態的,並且每個輸入文件都有可能。

我的代碼來讀取文件:

Function BuildArrayFromCsv(filepath) 'Function to read file and load into an array 

Const ForReading = 1 ' Declare constant for reading for more clarity 

Set inputFile = FileSysObj.OpenTextFile(filepath, ForReading, True) ' Set inputFile as file to be read from 

Dim row, column 
Dim fields(11) '12 fields per line 
inputFile.ReadAll 'read to end of file 
ReDim MyArray(11,inputFile.Line-2) 'current line, minus one for header, and minus one for starting at zero 
inputFile.close  'close file so that MyArray can be filled with data starting at the top 
Set inputFile = FileSysObj.OpenTextFile(filepath, ForReading, True) 'back at top 
inputFile.ReadLine 'skip header 


Do Until inputFile.AtEndOfStream 
    fields = Split(inputFile.Readline,",") 'store line in temp array 
    For column = 0 To 11 'iterate through the fields of the temp array 
     myArray(row,column) = fields(column) 'store each field in the 2D array with the given coordinates 
    Next 
    row = row + 1 'next line 
Loop 

inputFile.close 
End Function 
+0

什麼是你的問題/問題? –

+0

對不起。我編輯包括我的問題。 – user3352792

回答

3

在VBScript Dim name(n)創建大小的固定陣列的n + 1;這樣的野獸不能用/動態地覆蓋(如Split()返回)。證據

>> Dim fields(1) 
>> fields = Split("a b") 
>> 
Error Number:  13 
Error Description: Type mismatch 
>> Dim fields 
>> fields = Split("a b") 
>> WScript.Echo Join(fields) 
>> 
a b 
>> 

所以更換

Dim fields(11) '12 fields per line 

Dim fields 'should be 12 fields per line, checking the result of Split() advisable 
+0

解釋證據部分的格式:這是REPL會話的不變拷貝。 –