vb读取文本文件某行的内容

vb读取文本文件第二行的全部内容.

附:
文本文件路径:C:\1.txt
VB软件输出地方:Label1.caption

VB可以使用二进制方式打开文本文件,以Get 语句读到字节数组,再使用StrConv 函数将其转换为字符串,而后使用Split函数文本的字符串数组及总句数,使用InputBox 函数来输入需要读某行文本。

Get 语句

将一个已打开的磁盘文件读入一个变量之中。

StrConv 函数

返回按指定类型转换的 Variant (String)。

Split函数

返回一个下标从零开始的一维数组,它包含指定数目的子字符串。

InputBox 函数

在一对话框来中显示提示,等待用户输入正文或按下按钮,并返回包含文本框内容的 String。

以下是使用上述函数等的具体代码:

Private Sub Command3_Click()
    Dim strWj As String
    Dim strJ() As String
    Dim aryContent() As Byte
    Dim i As Long
    Dim j As Long
    CommonDialog1.CancelError = True ' è®¾ç½®â€œCancelError”为 True
    On Error GoTo ErrHandler
    CommonDialog1.Flags = cdlOFNHideReadOnly    ' è®¾ç½®æ ‡å¿—
    ' è®¾ç½®è¿‡æ»¤å™¨
    CommonDialog1.Filter = "All Files (*.*)|*.*|Text Files" & "(*.txt)|*.txt|Batch Files (*.bat)|*.bat"
    CommonDialog1.FilterIndex = 2    ' æŒ‡å®šç¼ºçœçš„过滤器
    CommonDialog1.ShowOpen    ' æ˜¾ç¤ºâ€œæ‰“开”对话框
    ' æ˜¾ç¤ºé€‰å®šæ–‡ä»¶çš„名字
    'MsgBox CommonDialog1.FileName
    Open CommonDialog1.FileName For Binary As #1
        ReDim aryContent(LOF(1) - 1)
        Get #1, , aryContent
    Close #1
    strWj = StrConv(aryContent, vbUnicode)
    Text1 = strWj
    strJ = Split(strWj, vbCrLf)
    i = UBound(strJ)
    Text2 = i + 1
    j = InputBox("输入需要显第几句", j)
    j = j - 1
    Label1.Caption = j + 1 & ":" & strJ(j)
    Exit Sub
ErrHandler:
    ' ç”¨æˆ·æŒ‰äº†â€œå–消”按钮
    Exit Sub
End Sub

温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-06-27
dim intCount as integer
dim s as string

intCount = 1

Open "C:\1.txt" For Input As #1
Do While Not EOF(1)
Line Input #1, s
if intCount=2 then
Label1.caption=s
exit do
end if
intCount = intCount + 1
Loop
第2个回答  推荐于2017-09-29
调试通过:
Private Sub Form_Load()
Dim s1 As String
Dim s2 As String
Open "c:\1.txt" For Input As #1
Line Input #1, s1
Line Input #1, s2
Label1.caption = s2
Close #1
End Sub本回答被提问者采纳