一问五不知吧 关注:22贴子:100
  • 2回复贴,共1

WORD文件名整理VBA命令

只看楼主收藏回复

Sub mySaveAs()
'
Dim i As Long, st As Single, mypath As String, fs As FileSearch
Dim myDoc As Document, n As Integer
Dim strpara1 As String, strpara2 As String, docname As String, a
On Error GoTo hd
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "请选定任一文件,确定后将重命名全部WORD文档"
If .Show <> -1 Then Exit Sub
st = Timer
mypath = .InitialFileName
End With
Application.ScreenUpdating = False
If Dir(mypath & "另存为", vbDirectory) = "" Then MkDir mypath & "另存为" '另存为文档的保存位置
Set fs = Application.FileSearch
With fs
.NewSearch
.LookIn = mypath
.FileType = msoFileTypeWordDocuments
If .Execute(msoSortByFileName) > 0 Then
For i = 1 To .FoundFiles.Count
If InStr(fs.FoundFiles(i), "~$") = 0 Then
Set myDoc = Documents.Open(.FoundFiles(i), Visible:=False)
With myDoc
strpara1 = Replace(.Paragraphs(1).Range.Text, Chr(13), "")
strpara1 = Left(strpara1, 10)
strpara2 = Replace(.Paragraphs(2).Range.Text, Chr(13), "")
If Len(strpara1) < 2 Or Len(strpara2) < 2 Then GoTo hd
docname = strpara1 & "_" & strpara2
docname = CleanString(docname)
For Each a In Array("\", "/", ":", "*", "?", """ ", "<", " >", "|")
docname = Replace(docname, a, "")
Next
.SaveAs mypath & "另存为\" & docname & ".doc"
n = n + 1
.Close
End With
End If
Next
End If
End With
MsgBox "共处理了" & fs.FoundFiles.Count & "个文档,保存于目标文件夹的名称为“另存为”的下一级文件夹中。" _
& vbCrLf & "处理时间:" & Format(Timer - st, "0") & "秒。"
Application.ScreenUpdating = True
Exit Sub
hd:
MsgBox "运行出现意外,程序终止!" & vbCrLf & "已处理文档数:" & n _
& vbCrLf & "出错文档:" & vbCrLf & fs.FoundFiles(i)
If Not myDoc Is Nothing Then myDoc.Close
End Sub


IP属地:河南1楼2012-06-01 09:21回复
    这段代码可以不打开文档提取指定文件夹的WORD文档的中的第1段的前10个字符和第2段落的文字作为并被提取文档的“另存为”文件的文件名,如果想修改提取的文字内容,可修改
    strpara1 = Replace(.Paragraphs(1).Range.Text, Chr(13), "")
    strpara1 = Left(strpara1, 10)
    strpara2 = Replace(.Paragraphs(2).Range.Text, Chr(13), "")
    这三行。前两行是提取第一段的前10字符,后一行是提取第二段的内容。如果文档标题是第一段,第二段是作者,把strpsra1=Left(strpara1, 10)一行删除,如果没有标题,第一段是一大段内容,把strpara2一行删除。
    这段代码是我请@sylun 为我编写的。深表感谢之意!!!


    IP属地:河南2楼2012-06-01 09:37
    回复
      去年看到这个帖子时,惊为天人;
      现在,了解了类模块和API后再看,已是沧海桑田了....


      IP属地:河南3楼2013-10-14 16:12
      回复