2015-10-21 45 views
0

我試圖將文本文件中的特定行存儲到變量中,首先驗證每行,然後將每個有效行分割爲二維動態數組中的列。我有這樣的代碼:將從文本文件中提取的驗證數據存儲到變量中

Option Explicit 
Sub GetMaterialFromText() 
Dim Delimiter As String 
Dim TextFile As Integer 
Dim FilePath As String 
Dim FileContent As String 
Dim LineArray() As String 
Dim DataArray() As String 
Dim TempArray() As String 
Dim Rw As Integer, Cl As Integer, x As Integer, y As Integer 
'inputs 
Delimiter = ":" 
FilePath = "C:\Users\jlopez\Desktop\2018\material.txt" 
Rw = 0 
'open the text file in a read state 
TextFile = FreeFile 
Open FilePath For Input As TextFile 
'store file content iside a variable 
FileContent = Input(LOF(TextFile), TextFile) 
'close text file 
Close TextFile 
'separate out lines of data 
LineArray() = Split(FileContent, vbCrLf) 

'read data into an array variable 
For x = LBound(LineArray) To UBound(LineArray) 
If Module1.TEXTCOUNTER(LineArray(x), ":") >= 30 Then 
'split up line of text by delimiter 
TempArray = Split(LineArray(x), Delimiter) 
'determine how many columns are needed 
Cl = UBound(TempArray) 
're-adjust array bundaries 
ReDim Preserve DataArray(Rw, Cl) '<-- here is the alert of Run-Time Error 9 
'load line of data into array variable 
For y = LBound(TempArray) To UBound(TempArray) 
DataArray(Rw, y) = TempArray(y) 
Next y 
End If 
'new line 
Rw = Rw + 1 
Next x 

End Sub 

UDF TEXTCOUNTER代碼是這樣的:

Function TEXTCOUNTER(Text As String, ToCount As String) As Integer 
Application.Volatile 
With Application.WorksheetFunction 
TEXTCOUNTER = Len(Text) - Len(.Substitute(Text, ToCount, "")) 
End With 
End Function 

,但是我收到一個運行時錯誤「9」,我認爲這是由動態數組引起的,但我不知道知道如何使它正確運行,有人可以幫助我嗎?

+0

錯誤發生在哪裏?我們需要更多信息。你有沒有嘗試過自己調試呢? –

+0

此行發生錯誤: **保留DataArray(Rw,Cl)'< - 這裏是運行時錯誤9 ** 的警報,並且是。我確實試圖解決這個問題,但我也無法實現。 – JoeJoe

回答

0

問題在於redim preserve,因爲它只能更改最後一個維度的邊界,而不是第一個維度,請參閱redim - VBA language reference

如果一行內的元素數量逐行不同,並且將實際行的第二維的上限重新調整爲數字,那麼您可能會遇到另一個問題,即小於元素數以前的行,因爲你會放棄值。

我會使用1個dimansional動態數組來存放數據,其中每個元素本身就是一個動態數組。

Dim DataArray() 
... 
ReDim DataArray(Ubound(LineArray)) 

For x = LBound(LineArray) To UBound(LineArray) 
    If Module1.TEXTCOUNTER(LineArray(x), ":") >= 30 Then 
    'split up line of text by delimiter 
    DataArray(x) = Split(LineArray(x), Delimiter) 
    End If 
Next x 

要訪問元素,請使用DataArray(x)(y)語法,而不是DataArray(x,y)。

相關問題