2013-03-13 122 views
2

行「輸入#1,數字(行,列)」給我一個運行時錯誤9.任何想法?代碼中的評論解釋了應該發生的事情。視覺基礎Excel txt輸入文件

Sub InputImage() 
'brings a text file to the workbook 

Dim Row As Long, Column As Long, Nrow As Long, Ncolumn As Long 

    Call MsgBox("Navigate to a folder that contains the file image.txt in the 00_18 folder") 
    ' The next statement will open a dialogue box that will let 
    ' the user navigate to any folder on their system 
    Call Application.GetOpenFilename 
Open "image.txt" For Input As #1 

Dim Buffer As String 
Line Input #1, Buffer 'read a whole line of characters from 
    'file #1 into the string variable buffer 

Line Input #1, Buffer 
Input #1, Buffer, Nrow 
Input #1, Buffer, Ncolumn 

Dim Numbers(1 To 4, 1 To 4) As Long 
For Row = 1 To Nrow 
    For Column = 1 To Ncolumn 
     Input #1, Numbers(Row, Column) 
    Next Column 
Next Row 

Close #1 

End Sub 
+0

發生錯誤時行和列的值是什麼? – 2013-03-13 06:11:41

+0

錯誤9下標超出範圍意味着您的數組和您的文本文件中的數據不是好友:-)。如果您可以將要從文件image.txt讀取的數據發佈到數組Numbers,這將會很有幫助。 – dee 2013-03-13 07:12:15

+1

你知道你可以閱讀你的文本文件作爲查詢使用ADO如果它的分隔 - 看看[MSDN腳本診所:很多ADO關於文本文件](http://msdn.microsoft.com/en-us/library/ms974559。 aspx) – 2013-03-13 09:19:06

回答

0

試試下面的代碼:

Option Base 1 
Sub InputImage() 
'brings a text file to the workbook 
    Dim j As Integer, i As Integer 
    Dim Row As Long, Column As Long, Nrow As Long, Ncolumn As Long 

    Call MsgBox("Navigate to a folder that contains the file image.txt in the 00_18 folder") 
    ' The next statement will open a dialogue box that will let 
    ' the user navigate to any folder on their system 
    Call Application.GetOpenFilename 


    Dim FileNum As Integer 
    Dim DataLine As String 

    FileNum = FreeFile() 
    Open "image.txt" For Input As #FileNum 


    j = 1 
    While Not EOF(FileNum) 
     Line Input #FileNum, DataLine ' read in data 1 line at a time 
     ' decide what to do with dataline, 
     ' depending on what processing you need to do for each case 
     'you can use split function to split DataLine with required delimiter which will return you an array. 
     a = Split(DataLine, vbTab) 

     For i = 1 To UBound(a) 
      Cells(j, i).Value = a(i) 
     Next 
     j = j + 1 
    Wend 


End Sub 

假設你image.txt像下面的圖片。

enter image description here