Function lines(txtpath As String, ByVal startline As Integer, linenum As Integer) As String '显示 txtpath 文件的从startline 行开始的 linenum 行的内容
lines = ""
Dim filetxt As String, x As Variant, i As Integer
filetxt = String(FileLen(txtpath), " ")
Open txtpath For Binary As 1
Get #1, , filetxt
Close 1
x = Split(filetxt, vbCrLf)
msgbox ubound(x)+1 '行数
If startline > UBound(x) Then MsgBox "行溢出", 64, "err!": Exit Function
If startline <= UBound(x) Then
If startline + linenum <= UBound(x) Then
For i = startline To startline + linenum - 1
lines = lines & x(i) & " "
Next
Else
For i = startline To UBound(x)
lines = lines & x(i) & " "
Next
End If: End If
Private Function ReadFileLine(cfile As String, cLine As Integer) As String
Dim I As Integer
Dim fsoTest As New FileSystemObject, file1 As File, ts As TextStream
Set file1 = fsoTest.GetFile(cfile)
Set ts = file1.OpenAsTextStream(ForReading)
I = 1
Do While Not ts.AtEndOfStream
If I <> cLine Then
ts.ReadLine
Else
ReadFileLine = ts.ReadLine
End If
I = I + 1
Loop
MsgBox "总行数" & I
Set ts = Nothing
End Function
Private Sub Form_Load()
MsgBox "读取行的内容为:" & (ReadFileLine("f:\test.txt", 3))
declare function sendmessage lib "user32" alias "sendmessagea" (byval hwnd as long, byval wmsg as long, byval wparam as long,lparam as any) as long
public const em_getlinecount=&hba
public const em_getline=&hc4
在form1的代码模块中写如下代码:
private sub command1_click()
dim str(256) as byte
str(1)=1 '最大允许存放256个字符
'获取总行数,结果显示在文本框txtlinecount中
txtlinecount=sendmessage(text1.hwnd,em_getlinecount,0,0)
'获取第3行的数据放在str中,转换为字符串后显示在文本框txtstring中
sendmessage text1.hwnd,em_getline,2,str(0)
txtstring= strconv(str,vbunicode)
end sub
之后,按f5运行程序,在多行文本框中随便键入几行文字,然后按下[确定]按钮。
我是用 Line Input 语句来实现的。
你用 DO 循环 加 eof(#n) 再来个计数变量就可以很好的的控制读取固定的行,一次整行读入。这样的代码很简单!:
'打开文件 c:\Escreps.prn
Open "c:\Escreps.prn" For Input As #1
'取文件内容,这种是知道文件的固定行数
For i = 1 To 24
Line Input #1, temp
Select Case i
Case 8 '例如要处理第8行
'在这里可以处理 TEMP 读取的内容
End Select
Next i
Close #1
'*-----------------不知道文件总行数的时候用这种办法。
Do While Not EOF(1)
'------------取文件内容
Line Input #10, DateSr
i=i+1
Select Case i '这个你也可以用其他判断语句。
Case 8 '例如要处理第8行
'在这里可以处理 TEMP 读取的内容
End Select
LOOP