【问题标题】:Renaming Documents as specific text within document将文档重命名为文档中的特定文本
【发布时间】:2017-07-10 15:11:10
【问题描述】:

所以我有超过 800 个文档需要重命名。它们都包含一个名为“标题:”的特定部分。问题是,这出现在每个文档的不同位置。它基本上是之后的文本,我正在寻找它的名字。

Sub Macro1()
Dim strFolder As String
Dim strDoc As String
Dim wordApp As Word.Application
Dim wordDoc As Word.document

Set wordApp = New Word.Application
wordApp.Visible = True

Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
.Title = "D:\Test\"
If .Show = -1 Then
    strFolder = .SelectedItems(1) & "\"
Else
    MsgBox "You did not select the folder that contains the documents."
    Exit Sub
End If
End With

MkDir strFolder & "Processed"

strDoc = Dir$(strFolder & "*.docx")
While strDoc <> ""
Set wordDoc = Word.Documents.Open(strFolder & strDoc)
With wordDoc
    .Content.Select
    With wordApp.Selection.Find
        .Text = "Your establishment name [0-9]{4}"
        .MatchWildcards = True
        .wrap = wdFindStop
        .Execute
    End With
    .SaveAs strFolder & "Processed\" & Right(wordApp.Selection, 4) & ".docx"
    .Close
End With
strDoc = Dir$()
Wend

wordApp.Quit
Set wordApp = Nothing
End Sub

我发现了 Silkroad 完成的一些代码,看起来完全符合我的要求,但它出错了。

这基本上是在 WordApp.Selection.Find 行出错:

运行时错误 91:对象变量 或未设置块变量

请帮我解决问题。

【问题讨论】:

  • 不应该 Word.DocumentswordApp.Documents 吗?似乎wordApp.Selection 将保持Nothing 否则,这解释了With wordApp.Selection.Find 将如何抛出该错误。
  • 好地方!那么它现在正在尝试运行,让我们看看它是否能够提取我想要的信息!手指交叉!
  • 所以与其重命名它们,不如打开它们,然后对其进行崩溃。尽管它设法找到了我想要的“标题:”这个词。但我希望它在该标题之后提取信息。哎呀。

标签: vba ms-word save rename


【解决方案1】:

使用下面的代码

With wordDoc
    .Content.Select
   'With wordApp.Selection.Find (Remove this line)
      ' Add the  wordApp.Selection.Find as below
    wordApp.Selection.Find.Text = "Your establishment name [0-9]{4}"
    wordApp.Selection.Find.MatchWildcards = True
    wordApp.Selection.Find.wrap = wdFindStop
    wordApp.Selection.Find.Execute
   End With  (Remove this line)
.SaveAs strFolder & "Processed\" & Right(wordApp.Selection, 4) & ".docx"
.Close
End With

With 块中的 With 块不能按预期工作,因为它总是先取第一个 with 块,然后再取第二个 with。 删除其中一个,它会正常工作。

【讨论】:

  • 无论我如何尝试,仍然无法正常工作。只需打开一个文档然后放弃!
猜你喜欢
  • 1970-01-01
  • 2012-12-30
  • 1970-01-01
  • 2020-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多