|
- Sub 批量提取标题为文件名()
- Dim myDialog As FileDialog, oDoc As Variant, myDoc As Document
- Dim myRange As Range, oldName As String, ErrArray() As Variant
- Dim oArray As Variant, NewName As String
- On Error Resume Next '忽略错误
- '定义一个导致文件名出错的数组
- ErrArray = Array("", "/", "*", "?", "<", ">", "|", """", Chr(9), Chr(11), Chr(13))
- '定义一个文件夹选取对话框
- Set myDialog = Application.FileDialog(msoFileDialogFilePicker)
- With myDialog
- .Filters.Clear '清除所有文件筛选器中的项目
- .Filters.Add "所有 WORD 文件", "*.doc", 1 '增加筛选器的项目为所有WORD文件;其中1表示文件筛选器的默认选项(表示为第一项),以此类推
- .AllowMultiSelect = True '允许多项选择
- If .Show <> -1 Then Exit Sub
- For Each oDoc In .SelectedItems '在所有选取项目中循环
- NewName = ""
- '以隐藏方式打开Word文档
- Set myDoc = Word.Documents.Open(FileName:=oDoc, Visible:=False)
- Set myRange = myDoc.Paragraphs(8).Range '取得第1个段落区域
- oldName = Application.CleanString(myRange.Text) '清除非打印字符
- For Each oArray In ErrArray '遍历替换
- oldName = Replace(oldName, oArray, "")
- Next
- myDoc.Close False '关闭文档
- If Len(oldName) < 1 Then '如果长度小于1不处理
- Else '进行重命名操作
- NewName = .InitialFileName & oldName & ".doc"
- '如果当前文件夹中没有此文件名
- If Dir(NewName, vbDirectory) = "" Then
- Name oDoc As NewName '直接命名
- Else '如果存在,则按时间序列数加命名
- NewName = Replace(NewName, ".doc", "")
- NewName = NewName & Date
- NewName = Replace(NewName, ".", "")
- NewName = NewName & ".doc"
- Name oDoc As NewName
- End If
- End If
- Next
- End With
- End Sub
复制代码 问题是你的标题应该有固定行,现在是第8行。
请高手指点一下如何取二行、三行为文件名 |
|