所以我有一个文本文件,其中有多行,每行都有以分隔符分隔的条目。我设法将数据分解并将它们放入多维数组中,请参阅下面的代码。
每行具有由分隔符分隔的不同数量的条目
Public Sub testarr()
Dim i As Integer
Dim j As Integer
Dim iFile As Integer
Dim TotalRows() As String
Dim TotalColumns() As String
Dim sData As String
Dim MyArray() As String
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Const forReading = 1
filepath = "C:\test1"
Set F = fso.OpenTextFile(filepath, forReading) 'open file for reading
y = 1
n = 5 'i've called a function to retrieve num of lines
'breaking into separate lines
For i = 1 To n
strContents = F.readline
strconts = strconts & vbCrLf & strContents
Debug.Print strconts
Next
Debug.Print strconts
TotalRows() = Split(strconts, vbNewLine)
'ReDim Preserve TotalRows(y)
'TotalRows = Split(sData, vbCrLf)
For y = 1 To 5
Debug.Print TotalRows(y)
Next y
'trying to separate each roads by the delimeters
For x = 1 To n
For y = 1 To 5
TotalColumns(x) = Split(TotalRows(y), "|")
Next y
Next x
上面的分割行,但每行都是相同的
For i = LBound(TotalRows) To UBound(TotalRows)
For j = LBound(TotalColumns) To UBound(TotalColumns)
MyArray(i, j) = TotalColumns(j)
Debug.Print MyArray(i, j)
Next
Next
End Sub
也许还有另外一个建议要做到这一点。我只是想能够检索特定行和列数组的条目(第2行,第3列)。但是每一行都有不同数量的条目,所以我不想定义列数,但会定义行数。
答案 0 :(得分:0)
这可能就是您之后的代码
Option Explicit
Public Sub testarr()
Const forReading = 1
Dim filepath As String
filepath = "C:\test1"
Dim strconts As String
With CreateObject("Scripting.FileSystemObject") 'create and reference FilSystemObject object
With .OpenTextFile(filepath, forReading) 'open file for reading and reference it
'breaking into separate lines
Do While .AtEndOfStream <> True 'read the file till its last line
strconts = strconts & .ReadLine & vbCrLf
Loop
.Close 'close referenced file
End With
End With
Dim TotalRows As Variant
TotalRows = Split(strconts, vbNewLine)
ReDim TotalColumns(LBound(TotalRows) To UBound(TotalRows)) As Variant 'dim your TotalColumns array with same rows number as TotalRows
Dim i As Integer, nCols As Long, nColsMax As Long
For i = LBound(TotalRows) To UBound(TotalRows)
TotalColumns(i) = Split(TotalRows(i), "|") 'have each TotalColumn element store an array
nCols = UBound(TotalColumns) - LBound(TotalColumns)
If nCols > nColsMax Then nColsMax = nCols 'store maximum number of columns across TotalColumns arrays
Next
ReDim MyArray(LBound(TotalColumns) To UBound(TotalColumns), 0 To nColsMax) As String 'size MyArray to the same rows number of TotalColumns and the maximum number of columns
Dim j As Integer
For i = LBound(TotalColumns) To UBound(TotalColumns)
For j = LBound(TotalColumns(i)) To UBound(TotalColumns(i))
MyArray(i, j) = TotalColumns(i)(j)
Debug.Print MyArray(i, j)
Next
Next
End Sub
当然这段代码可以进一步折叠,但这是你以后可以做的事情
答案 1 :(得分:0)
您可以使用“锯齿状”数组:
'...
TotalRows() = Split(strconts, vbNewLine)
For x = lbound(TotalRows) to unbound(TotalRows)
TotalRows(x) = Split(TotalRows(x), "|")
Next x
'....
现在每个“行”都是一个数组,所以它就像是:
blah = TotalRows(2)(2)
获取第三行的第三项。显然,在访问每个子数组时,您需要进行一些边界检查。