|
- '这个贴我在Excel VBA中已经回复过了:
- Sub test()
- Dim i%, j%, d, s, arrByte() As Byte
- Set d = CreateObject("Scripting.Dictionary")
- Application.ScreenUpdating = False
- FileName = ThisDocument.Path & "" & Dir(ThisDocument.Path & "" & "*.txt") '获取当前目录下的txt文件
- If Len(Dir(ThisDocument.Path & "" & "*.txt")) Then '判断是否存在txt文件
- Open FileName For Binary Access Read As #1
- ReDim arrByte(LOF(1) - 1)
- Get #1, , arrByte
- Close #1
- s = Split(ByteToStr(arrByte, "UTF-8"), vbNewLine) '调用ByteToStr函数
- Else
- MsgBox "当前目录下没有txt文件!": Exit Sub '当前目录下没有txt文件,退出程序
- End If
- If UBound(s) < 0 Then MsgBox "txt文件中没有数据!": Exit Sub 'txt文件中没有内容,退出程序
- For i = 0 To UBound(s)
- d(Trim(s(i))) = ""
- Next
- t = ""
- j = ThisDocument.Paragraphs.Count '获取文档总段数
- For i = 1 To ThisDocument.Paragraphs.Count
- If d.Exists(Replace(ThisDocument.Paragraphs(i).Range.Text, Chr(13), "")) Then
- t = Replace(ThisDocument.Paragraphs(i).Range.Text, Chr(13), "")
- d(t) = Array(i, i) '第一个参数记录段落开始
- Else
- If t <> "" Then d(t) = Array(d(t)(0), i) '第二个参数记录段落结束
- End If
- Next
- i = 0
- For Each tt In d.Keys '按先后顺序复制到文档最后
- ThisDocument.Range(ThisDocument.Paragraphs(d(tt)(0)).Range.Start, ThisDocument.Paragraphs(d(tt)(1)).Range.End).Select '选中
- Selection.Copy '复制
- If i = 0 Then
- ThisDocument.Range.InsertParagraphAfter '在文档后插入一行
- i = i + 1
- End If
- Selection.EndKey Unit:=wdStory '光标移到文档尾
- Selection.Paste '粘贴
- Next
- ThisDocument.Range(ThisDocument.Paragraphs(1).Range.Start, ThisDocument.Paragraphs(j).Range.End).Select '选中原来的内容
- Selection.Delete '删除
- Application.ScreenUpdating = True
- MsgBox "处理完成!", "64", "温馨提示"
- End Sub
- Function ByteToStr(arrByte, strCharset As String) As String 'ByteToStr函数读取UTF-8或Unicode编码的内容
- With CreateObject("Adodb.Stream")
- .Type = 1
- .Open
- .Write arrByte
- .Position = 0
- .Type = 2
- .Charset = strCharset
- ByteToStr = .Readtext
- .Close
- End With
- End Function
复制代码
|
|