VB 查找关键字 并输出保存成TXT问题,谢谢高手:P
我的邮箱 512401@sohu.com
3Q 展开
给个邮箱,我发给你。
Dim WeiZhi As Integer
Private Sub cmdFind_Click()
'查找指定文本出现的位置
If Len(txtFind.Text) > 0 Then
WeiZhi = InStr(txtFile.Text, txtFind.Text)
End If
If WeiZhi > 0 Then
txtSub.Text = Mid(txtFile.Text, WeiZhi, 30)
cmdSave.Enabled = True
End If
End Sub
Private Sub cmdOpen_Click()
Dim Str As String
With CommonDialog1
.InitDir = "D:\"
.Filter = "文本文件|*.txt"
.ShowOpen
End With
'如果没有指定文本名则退出
If Len(CommonDialog1.FileName) = 0 Then Exit Sub
'打开指定文本
Open CommonDialog1.FileName For Input As #1
txtFile.Text = ""
While Not EOF(1)
Input #1, Str
txtFile.Text = txtFile.Text & Str
Wend
Close #1
End Sub
Private Sub cmdSave_Click()
Dim Str As String
With CommonDialog1
.InitDir = "D:\"
.Filter = "文本文件|*.txt"
.ShowSave
End With
Str = txtSub.Text
'如果没有指定文本名则退出
If Len(CommonDialog1.FileName) = 0 Then Exit Sub
'写入指定文本
Open CommonDialog1.FileName For Output As #1
Write #1, Str
Close #1
End Sub
Private Sub cmdExit_Click()
'退出程序
End
End Sub
Private Sub txtFind_GotFocus()
txtFind.Text = ""
cmdFind.Enabled = False
End Sub
Private Sub txtFind_KeyUp(KeyCode As Integer, Shift As Integer)
If Len(txtFind.Text) > 0 Then
cmdFind.Enabled = True
Else
cmdFind.Enabled = False
End If
End Sub
Rem 六个控件,三个text控件:test1原文本,test2关键字,test3结果;三个Command控件:command1查找,command2保存,command3退出
Rem 设计界面时,需要在属性对话框内对test1和test3进行设置:MultiLine = True,ScrollBars=2
Private Sub Command1_Click()
Dim source, temp, i
source = "d:\sq.txt" '设置源文件
Rem test1里加载txt文件
If Dir(source) = "" Then MsgBox "源文件找不到!请确认文件路径和路径名!": Exit Sub
Open source For Binary As #1
test1.Text = StrConv(InputB(LOF(1), 1), vbUnicode)
Close #1
If test2.Text = "" Then MsgBox "请输入关键字!": Exit Sub
Rem 在test3里列出所有包含关键字test2的句子(同时显示关键字后长度30字节)
test3.Text = ""
For i = 1 To Len(test1.Text) - Len(test2.Text) + 1
temp = Mid(test1.Text, i, Len(test2.Text))
If temp = test2.Text Then
temp = Mid(test1.Text, i, Len(test2.Text) + 30)
temp = Replace(temp, vbCrLf, " ") '结果句子中的回车均替换为空格,若不想要这个功能,此行可删除
test3.Text = test3.Text & vbCrLf & temp
End If
Next
End Sub
Rem 将test3的结果输出保存成txt文件
Private Sub Command2_Click()
Dim target
target = "d:\target.txt" '设置结果文件
If test3.Text = "" Then MsgBox "结果为空,因此不予保存!": Exit Sub
Open target For Output As #1
Print #1, test3.Text
Close #1
End Sub
Private Sub Command3_Click()
End
End Sub
Private Sub Form_Activate()
Me.Caption = "关键字搜索"
test1.Text = "原文本"
test2.Text = "请输入关键字"
test3.Text = ""
Command1.Caption = "查找"
Command2.Caption = "保存"
Command3.Caption = "退出"
End Sub