将从文本文件中提取的验证数据存储到变量中

时间:2015-10-21 16:32:45

标签: arrays vba text-files

我尝试将文本文件中的特定行存储到变量中,首先验证每一行,然后将每个有效行拆分为二维动态数组中的列。我有这段代码:

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

但我收到了运行时错误&#39; 9,我认为它是由动态阵列引起的,但我不知道如何让它正确运行,有人可以帮忙我吗?

1 个答案:

答案 0 :(得分:0)

问题在于redim保留,因为它只能更改最后一个维度的边界,而不是第一个维度的边界,请参阅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)。