当前位置:编程学习 > VB >>

vb如何快速读取某一行

我用open语句打开了一个文件,但是我想快速的读取中间的第N行,而不是一行一行的读到第N行,请问各位有什么号的方法没咯!
答案:Private Sub Form_Load()

Dim By() As Byte
Dim StrA As String
Dim Data() As String
Dim n As Integer

'二进制读出,而不是一行一行!
Open "E:\我的文档\我不允许你.txt" For Binary As #1
ReDim By(1 To LOF(1))
Get #1, , By
Close #1
'转成文本
StrA = StrConv(By, vbUnicode)
'以回车划分行
Data = Split(StrA, vbNewLine)
'第几行?
n = InputBox("第几行?", "询问标题", 5)
'输出内容,因为是以0为开始的,所以要n-1才是所求的内容
MsgBox Data(n - 1)

End Sub

下面这个是我整理过的代码,经过测试的,你可以试试,


'***********************************************************************************************************************************************************
'模块部分
Public Const EM_GETLINE = &HC4
Public Const EM_LINELENGTH = &HC1
Public Const EM_LINEINDEX = &HBB

'窗体部分
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hWnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Declare Sub RtlMoveMemory Lib "KERNEL32" (lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)
'***********************************************************************************************************************************************************
dim hang '定义了要选取的第N行字符串
Sub TB_GetLine(ByVal hWnd As Long, ByVal whichLine As Long, Line As String)
Dim length As Long, bArr() As Byte, bArr2() As Byte, lc As Long
lc = SendMessage(hWnd, EM_LINEINDEX, whichLine, ByVal 0&)
length = SendMessage(hWnd, EM_LINELENGTH, lc, ByVal 0&)
If length > 0 Then
ReDim bArr(length + 1) As Byte, bArr2(length - 1) As Byte
Call RtlMoveMemory(bArr(0), length, 2) '准备一个存储器,传递消息之前先在存储器的前两个字节填入存储器的长度
Call SendMessage(hWnd, EM_GETLINE, whichLine, bArr(0))
Call RtlMoveMemory(bArr2(0), bArr(0), length)
Line = StrConv(bArr2, vbUnicode)
Else
Line = ""
End If
End Sub
'***********************************************************************************************************************************************************
Private Sub Command1_Click()
text3.text=hang
Dim S As String
Call TB_GetLine(Text1.hWnd, hang, S)
Text2.Text = S
End Sub
'***********************************************************************************************************************************************************

在窗体上建立三个textbox控件
text1设置成多行文本格式,是被查找的对象
text2是读取结果
text3是需要查找的第N行
在窗体上添加一个command命令按钮,是读取的过程

国庆节到了,祝你节日快乐!

VB的顺序文件只能通过循环。一行一行的读下去。直到你想要的那行。

Dim TextLineOpen "1.txt" For Input As #1 ' 打开文件。i=0Do While Not EOF(1) ' 循环至文件尾。 i=i+1 Line Input #1, TextLine if i=text1.text then
Debug.Print TextLine

goto closefile



endifLoopclosefile:Close #1

搜索文件,找到回车符,第i行就在第i-1个回车符和第i个回车符之间

上一个:VB的代码问题。急!!!
下一个:Vb如何修改浏览器主页

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,