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运行程序,在多行文本框中随便键入几行文字,然后按下[确定]按钮,出现如图画面,说明程序正确统计出了总行数和第3行的文字。
两点补充说明:在调用SendMessage获取第N行字符串时,lParam需要说明为字节数组,在调用完成后,再将字节数组转换为字符串;另外,调用前必须在lParam的前两个字节指明允许存放的最大长度,其中第一个字节为低位,第二个字节为高位,本例将高位(即str(1))置1.说明最大允许存放256个字符。
Public Const EM_GETLINECOUNT = &HBA
Public Const EM_GETLINE = &HC4
Public Const EM_LINEINDEX = &HBB
Public Const EM_LINELENGTH = &HC1
Declare Function SendMessage Lib "user32" Alias "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Declare Sub RtlMoveMemory Lib "KERNEL32" (lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)
添加一个窗口,并在窗口中添加如下控件:
textbox,command
Private Sub Command1_Click()
'其中的21即为要读取的行数
Dim S As String, Length As Integer, pos As Long
上面的两个api你可以自己查看相关资料!
下面再给一个不用api的例子:
Function textboxgetline(txt As textbox, ByVal n As Long) As Variant
Dim s As String, pos As Long, pos2 As Long, lineindex As Long
textboxgetlind = Null
lineindex = 0
pos = 1
s = txt.Text
Do
If lineindex = n Then
pos2 = InStr(pos, s, vbCrLf)
If pos2 > 0 Then
textboxgetline = Mid(s, pos, pos2 - pos)
Else
textboxgetline = Mid(s, pos)
End If
Else
pos = InStr(pos, s, vbCrLf)
If pos > 0 Then pos = pos + 2 '跳过vbcrlf
End If
lineindex = lineindex + 1
Loop Until pos = 0 '继续寻找vbcrlf,直到没有vbcrlf为止
End Function
注意需要在工程中引用 micrsoft scriping runtime 项目
Dim wj As TextStream
Dim file As New FileSystemObject
Set wj = file.OpenTextFile(pt, , True) 'pt为打开TXT文件路竟
'对变量进行全局复制
Do While wj.AtEndOfLine = False
ReadPostion wj.ReadLine 'readline 读取一行 (过程不要管)
Loop
wj.Close
Set wj = Nothing
Set file = Nothing
Dim wj As TextStream
Dim file As New FileSystemObject
Set wj = file.OpenTextFile(pt, , True) 'pt为打开TXT文件路竟
for i=1 to 行的数量
if i=行的数量 then
mid(ReadPostion wj.ReadLine,列的字符号位置,取出列的数量) 'readline 读取一行 (过程不要管)
else
wj.readline '
end if
next
这段代码效率不高,自己改进
Dim wj As TextStream
Dim file As New FileSystemObject
Set wj = file.OpenTextFile(pt, , True) 'pt为打开TXT文件路竟
for i=1 to 行的数量
if i=行的数量 then
mid(ReadPostion wj.ReadLine,列的字符号位置,取出列的数量) 'readline 读取一行 (过程不要管)
end if
next