VB操作文本文件的方法很多,下面的例子是我自己作项目或者回答网友提问时做的,很有代表性,希望能够给各位朋友一些启发.
'功能:删除、替换文本中一行,或者插入内容到文本中某一行 '作者: soho_andy (冰) '参数: 'strSourceFile 原始文件完整名 'strTargetFile 生成新文件的完整名 'intRow 操作的行数
Sub 操作文件中一行(strSourceFile As String, strTargetFile As String, intRow As Long) Dim filenum As Integer Dim fileContents As String Dim fileInfo() As String Dim i As Integer Dim j As Integer filenum = FreeFile Open strSourceFile For Binary As #filenum fileContents = Space(LOF(filenum)) Get #filenum, , fileContents Close filenum fileInfo = Split(fileContents, vbCrLf) '取出源文件行数,按照回车换行来分隔成数组 filenum = FreeFile If Dir(strTargetFile, vbNormal) <> "" Then Kill strTargetFile End If Dim Filestr() As String '删除一行代码块 Open strTargetFile For Append As #filenum '循环每一行 For i = 0 To UBound(fileInfo) - 1 If i <> intRow - 1 Then Print #filenum, fileInfo(i) End If Next Close #filenum '替换一行代码块 Open strTargetFile For Append As #filenum '循环每一行 For i = 0 To UBound(fileInfo) - 1 If i = intRow - 1 Then Print #filenum, "你要替换进去的内容" End If Next Close #filenum '插入一行代码块 Open strTargetFile For Append As #filenum '循环每一行 For i = 0 To UBound(fileInfo) - 1 If i = intRow - 1 Then Print #filenum, "你要插入到这行的内容" Print #filenum, fileInfo(i) '保留原来的行,位置后移一位 End If Next Close #filenum MsgBox "完毕" End Sub
'另外一个解决实际问题的例子 ' '网友的要求 '设有文件a.txt,其中存放了两行数据,数据用逗号分隔,现在要读取第一行的奇数位置的数据写入到另一个文本文件(b.txt)的第一行,类似地,把第二行的奇数位置的数据写入到第二行。 '比如: '文件a.txt如下: '1,2,3,4,5 '6,7,8,9,10 '操作完成后,文件b.txt应为 '1,3,5 '6,8,10
'作者: soho_andy (冰) '参数: 'strSourceFile 原始文件完整名 'strTargetFile 生成新文件的完整名
Sub 提取奇数位数据(strSourceFile As String, strTargetFile As String) Dim filenum As Integer Dim fileContents As String Dim fileInfo() As String Dim i As Integer Dim j As Integer Dim tmpDemData As String filenum = FreeFile Open strSourceFile For Binary As #filenum fileContents = Space(LOF(filenum)) Get #filenum, , fileContents Close filenum fileInfo = Split(fileContents, vbCrLf) '取出源文件行数,按照回车换行来分隔成数组 filenum = FreeFile tmpDemData = "" If Dir(strTargetFile, vbNormal) <> "" Then Kill strTargetFile End If Dim Filestr() As String
Open strTargetFile For Append As #filenum '循环每一行 For i = 0 To UBound(fileInfo) - 1 Filestr = Split(Trim(fileInfo(i)), ",") '按照逗号分隔每一行的数据 tmpDemData = "" For j = 0 To UBound(Filestr) '判断是否为奇数位 If (j Mod 2) = 0 Then tmpDemData = tmpDemData & Filestr(j) ElseIf j <> 0 And j <> UBound(Filestr) Then tmpDemData = tmpDemData & "," End If Next '保存一行如目标文件 Print #filenum, tmpDemData Next Close #filenum MsgBox "完毕" End Sub
Private Sub Command1_Click() 提取奇数位数据 "d:\aa.txt", "d:\bb.txt" End Sub |