VB如何读取txt文件

txt文件中有6行数据,想只读取1~5行的数据。通过点击command来实现读取后的数据到text当中,请问怎么实现?谢谢

可以用下面的方法读取

Private Sub Command1_Click()
    Dim text
    Dim line
    Open App.Path & "\test.txt" For Input As #1
    For i = 0 To 4
        Line Input #1, line
        text = text & line & vbCrLf
    Next i
    Close #1
    Text1.text = text
End Sub

测试工程见附件

追问

非常感谢,那要是只读取第二行到第四行怎么改呢?第一行不要,谢谢

追答

可以把读出来的整个文件内容,用 split 函数按回车换行符分割到数组中,然后在数组中你想要哪行就可以读哪行。

参考代码如下:

    Dim text As String
    Dim line As String
    Dim text_arr() As String
    Open App.Path & "\test.txt" For Input As #1
    Do While Not EOF(1)
        Line Input #1, line
        text = text & line & vbCrLf
    Loop
    Close #1
    text_arr = Split(text, vbCrLf)
    For i = 2 To 4
        Text1.text = Text1.text & text_arr(i) & vbCrLf
    Next i

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-05-16
下面将5行数据读到数组里;
dim i as integer
Dim MyLineStr(5) As String

'读取文件信息
Open 文件名标识符 For Input As #1 '以读的方式打开文件
for i=1 to 5
Line Input #1, MyLineStr(i)
next i
Close #1 ' 关闭文件。本回答被网友采纳
相似回答