0

所以我有许多文本文件,我正试图用 Visual Basic 阅读。它们都具有相同的格式:

[number of items in the file]
item 1
item 2
item 3
...etc.

我要做的是在第一行声明一个整数大小的数组,然后将每一行读入数组的相应部分(因此第 1 项将是数组 [0],第 2 项将是数组 [ 1]等。但是,我不确定从哪里开始。任何帮助将不胜感激。

4

4 回答 4

3

非常基本的东西(没有双关语):

Dim F As Integer
Dim Count As Integer
Dim Items() As String
Dim I As Integer

F = FreeFile(0)
Open "data.txt" For Input As #F
Input #F, Count
ReDim Items(Count - 1)
For I = 0 To Count - 1
    Line Input #F, Items(I)
Next
Close #F
于 2012-04-24T07:14:16.243 回答
1

试试这个 VB6

Dim file_id As Integer
Dim strline as string
Dim array_item() as string

'Open file
file_id = FreeFile
Open "C:\list.txt" For Input AS #file_id 

Dim irow As Integer
irow = 0    

'Loop through the file
Do Until EOF(file_id)

    'read a line from a file
    Line Input #file_id, strline

    'Resize the array according to the line read from file
    Redim Preserve array_item(irow)

    'put the line into the array
    array_item(irow) = strline

    'move to the next row
    irow = irow + 1
Loop

Close #file_id
于 2012-04-24T06:41:49.030 回答
0

您正在寻找的 VB 函数是“拆分”:

http://www.vb-helper.com/howto_csv_to_array.html

于 2012-04-24T05:23:39.417 回答
0

尝试这个:

Dim FullText As String, l() As String
'''Open file for reading using Scripting Runtime. But you can use your methods
Dim FSO As Object, TS As Object
Set FSO = createbject("Scripting.FileSystemObject")
Set TS = createbject("Scripting.TextStream")
Set TS = FSO.OpenTextFile(FilePath)
TS.ReadLine 'Skip your first line. It isn't needed now.
'''Reading the contents to FullText and splitting to the array.
FullText = TS.ReadAll
l = Split(FullText, vbNewLine) '''the main trick

拆分会自动调整 l() 的大小并存储所有数据。
现在 l() 数组拥有你想要的一切。

于 2012-10-11T20:02:19.570 回答