|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
Sub 循环遍历文件夹_doc_txt()
Dim t As Long, a As String, b As Long, c As Long, s As Section, j As Long
If MsgBox("是否处理 Word 文档(*.doc)? (否则处理文本文档(*.txt))", vbYesNo + vbExclamation, "循环遍历文件夹") = vbYes Then t = 1 Else t = 0
a = MsgBox("请选择——是:批量打印 否:批量合并 取消:批量转换", vbYesNoCancel + vbExclamation, "循环遍历文件夹")
If a = vbYes Then
b = 1
ElseIf a = vbNo Then
b = 2
If MsgBox("文档之间是否插入分页符?", vbYesNo + vbExclamation, "循环遍历文件夹") = vbYes Then c = 1 Else c = 0
Documents.Add
Else
b = 3
End If
On Error Resume Next
Dim fd As FileDialog, i As Long, doc As Document, p As String
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
If fd.Show = -1 Then p = fd.SelectedItems(1) Else Exit Sub
Set fd = Nothing
If MsgBox("Are you sure to process the folder " & p & " ?" & vbCr & "是否处理文件夹 " & p & " ?", vbYesNo + vbExclamation, "循环遍历文件夹") = vbNo Then Exit Sub
With Application.FileSearch
' .NewSearch
.LookIn = p
.SearchSubFolders = True
If t = 1 Then .FileName = "*.doc" Else .FileName = "*.txt"
' .FileType = msoFileTypeAllFiles
If .Execute > 0 Then
' MsgBox "There were " & .FoundFiles.Count & " file(s) found."
' For i = 1 To .FoundFiles.Count '逆序
For i = .FoundFiles.Count To 1 Step -1 '顺序
' MsgBox .FoundFiles(i)
If t = 1 Then Set doc = Documents.Open(FileName:=.FoundFiles(i)) Else Set doc = Documents.Open(FileName:=.FoundFiles(i), Encoding:=936)
If b = 1 Then
If t = 1 Then
For Each s In doc.Sections
With s.PageSetup
If .Orientation = wdOrientLandscape Then j = 1 Else j = 0
If .PaperSize <> wdPaperA4 Then .PaperSize = wdPaperA4: If j = 1 Then .Orientation = wdOrientLandscape
End With
Next
doc.PrintOut
doc.Close savechanges:=wdDoNotSaveChanges
ElseIf t = 0 Then
doc.PrintOut
doc.Close savechanges:=wdDoNotSaveChanges
End If
ElseIf b = 2 Then
doc.Content.Copy
doc.Close
ActiveDocument.Content.Paste
If c = 1 Then ActiveDocument.Content.InsertBreak Type:=wdPageBreak
Else
If t = 1 Then doc.SaveAs FileName:=Left(doc.FullName, Len(doc.FullName) - 4) & ".txt", FileFormat:=wdFormatText Else doc.SaveAs FileName:=Left(doc.FullName, Len(doc.FullName) - 4) & ".doc", FileFormat:=wdFormatDocument
doc.Close
End If
Next i
If b = 2 Then
Selection.HomeKey Unit:=wdStory
If c = 1 Then Selection.Delete Unit:=wdCharacter, Count:=1
MsgBox "合并完毕!共合并 " & .FoundFiles.Count & " 个文件!请自行保存!", vbOKOnly + vbExclamation, "循环遍历文件夹"
Exit Sub
End If
MsgBox "Complete! There were " & .FoundFiles.Count & " file(s) processed." & vbCr & "处理完毕!共处理 " & .FoundFiles.Count & " 个文件!", vbOKOnly + vbExclamation, "循环遍历文件夹"
Else
MsgBox "There were no files found." & vbCr & "未发现文件!", vbOKOnly + vbCritical, "循环遍历文件夹"
End If
End With
End Sub |
|