请问VB中如何读取txt文件的数据

请问如何用VB读取某个文本文件的某一行的数据
并将该行的值赋予某个变量
我不会用SQL之类的啊...所以希望大家能帮帮忙啊
比如说一个文本文件的路径为D:\date.txt,然后查找某一个字符并读取该行的下一行的数据,将该数据赋予变量a
请大家讲详细点啊
每一行代码有什么用都讲清楚啊
还有就是如何在读取数值后将一个新值写如到第n行的位置然后保存
读取搜索到的数值后的第n行的代码要怎么写?

1、新建一个标准的VB EXE工程,只有一个Form,Form上有两个按钮:Command1和Command2。

2、双击Command1添加如下代码

Private Sub Command1_Click()

    Dim strFile     As String

    Dim intFile     As Integer

    Dim strData     As String

     strFile = "c:\学生成绩.txt"

    intFile = FreeFile

    Open strFile For Input As intFile

    strData = StrConv(InputB(FileLen(strFile), intFile), vbUnicode)

    Debug.Print strData

    Close intFile

End Sub

3、按F8开始单步调试代码,点击Command1,进入单步调试功能,

4、多次按下F8或直接按下F5运行完成,就完成了读取文本文件内容并输出到立即窗口。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-25
Dim A, S As String

Dim FreeNum As Integer
FreeNum = FreeFile
'Freenum表示一个空闲的文件号
open "D:\date.txt" for input as #FreeNum
'这步是打开“date.txt”,for input表示以输入方式(即读取文件)打开。如果要写入文件则应该用output或append。

Do Until eof(FreeNum) '循环,直到文件结尾。Eof函数用来判断文件是否读完
Line Input #FreeNum, A
S = S + vbNewLine + A 'S用来保存整个文件
If A满足某个条件 And Not Eof(FreeNum) Then
Line Input #FreeNum, A '读取下一行的内容
Exit do '退出循环
End if
Loop
Close FreeNum

至于将一个新值写进第N行,则可以
Dim A, S, S1 As String

Dim FreeNum As Integer
FreeNum = FreeFile
'Freenum表示一个空闲的文件号
open "D:\date.txt" for input as #FreeNum
'这步是打开“date.txt”,for input表示以输入方式(即读取文件)打开。如果要写入文件则应该用output或append。

Do Until eof(FreeNum) '循环,直到文件结尾。Eof函数用来判断文件是否读完
Line Input #FreeNum, A
S1 = S1 + vbNewLine + A 'S用来保存1到n-1行的内容,S1用来表示n行以后的内容
If A满足新写一行的条件 Then
S = S1
S1 = ""
End if
Loop

Close FreeNum
Open "D:\date.txt" For Output As FreeNum
'关闭文件之后重新以Output的模式打开。
Print #FreeNum, S
Print #FreeNum, 新插入一行的内容
Print #FreeNum, S1
Close FreeNum
即可本回答被提问者采纳