|
1.Application.ScreenUpdating = False不知道能不能提高效率
大部分情况下,它都能至少提高一倍效率
2.使用集合或者字典应该也能提高不少- Option Explicit
- Sub Example()
- Application.ScreenUpdating = False
- Dim myFolder As FileDialog, sinStart As Single
- Dim myString As String, TimerUsed As Single
- Dim fso As Object, TxtFolderName As String
- Dim myTxt As String, txtFileName As String, NewName As String
- Dim FenDuan() As Variant, aArray, myArray() As String
- Dim DelText As String, strRep As String, i As Integer
- Dim aCollection As New Collection, bCollection As New Collection
- '以下代码以得所选文本文件的名称和文件夹名
- Set myFolder = Application.FileDialog(msoFileDialogFilePicker)
- With myFolder
- .Filters.Clear
- .AllowMultiSelect = False
- .Filters.Add "文本文件", "*.TXT"
- If .Show <> -1 Then Exit Sub
- sinStart = Timer
- txtFileName = .SelectedItems(1)
- TxtFolderName = .InitialFileName
- NewName = VBA.Replace(txtFileName, TxtFolderName, "")
- NewName = "Trim_" & NewName
- NewName = TxtFolderName & NewName '新文件名称是在原文件夹中加上"Trim_"+原文件名
- End With
- Set myFolder = Nothing '释放对象变量
- 'Application.ScreenRefresh '刷新屏幕
- DelText = "<<page" '设置需要删除的文本内容
- Set fso = CreateObject("Scripting.FileSystemObject") '创建一个系统文件
- Set a = fso.OpenTextFile(txtFileName, 1, 0) '打开文本文件
- myTxt = a.ReadAll
- a.Close '关闭
- FenDuan = Array(vbCrLf & " ", " ", " ", vbCrLf & DelText, "=" & vbCrLf, vbCrLf) '定义一些需要重理的内容,分别是回车换行符+两个空格,半角空格,全角空格,回车换行符+<<page,=+回车换行符,回车换行符
- For Each aArray In FenDuan '使用集合提高效率
- aCollection.Add aArray
- Next
- For Each aArray In aCollection '集合元素中循环
- Select Case aArray '看集合元素
- Case vbCrLf & DelText '回车换行符+<<page
- strRep = "↓" & DelText '替换为标识文本和原标记
- Case vbCrLf & " ", "=" & vbCrLf '这是关键,分页标记以=号结束
- strRep = "↓" '替换为标识文本
- Case Else '其它全部删除
- strRep = ""
- End Select
- myTxt = VBA.Replace(myTxt, aArray, strRep) '指定替换
- Next
- myArray = VBA.Split(myTxt, "↓") '以标识文本分隔形成数组
- Dim bCollection As New Collection
- For Each aArray In myArray
- bCollection.Add aArray
- Next
- myTxt = "" '初始化变量
- For Each aArray In bCollection '在集合中循环
- If VBA.InStr(aArray, DelText) Or aArray = "" Then
- ElseIf aArray Like "第*回" Then i = i + 1
- myTxt = myTxt & vbCrLf & " " & aArray
- ElseIf i = 1 Then
- myTxt = myTxt & " " & aArray
- i = i + 1
- ElseIf i = 2 Then
- myTxt = myTxt & " " & aArray
- i = 0
- Else
- myTxt = myTxt & vbCrLf & " " & aArray
- End If
- Next
- Set a = fso.CreateTextFile(NewName, True) '创建一个文本文件
- a.Write (myTxt) '将内存数据写入文本文件中
- a.Close '关闭
- TimerUsed = Timer - sinStart '耗时
- MsgBox "程序重理文本文件共用时" & TimerUsed & "秒!", vbInformation
- Application.ScreenUpdating = True
- End Sub
复制代码 |
|