VBA:选择事件Word文档

标签 vba excel ms-word

我最近学习了如何在Excel中通过VBA操作Word文档。我的问题是我希望我的宏能够确定具有正确文件名的事件 Word 文档,然后选择该文档并继续宏。我有下面的代码

Sub CreateNewWordFile()
  Dim wrd As Word.Application
  Dim Opfile As Object
  Dim AcFile As Object

  Set Opfile = GetObject(, "Word.Application")
  Debug.Print Opfile.Documents.count
  For Each AcFile In Opfile.Documents
    If AcFile = "SampleWord " & Format(Now, "mm-dd-yyyy") & ".docx" Then
      Set wrd = AcFile.Application
      With wrd
       .Activate
       .Selection.TypeParagraph
       .Selection.TypeParagraph
       .Selection.Font.Size = 20
       .Selection.TypeText "success"
       .ActiveDocument.Save
       GoTo Label1
      End With
    End If
  Next
  Set wrd = New Word.Application

 With wrd
   .Visible = True
   .Activate
   .Documents.Add
   With .Selection
       .ParagraphFormat.Alignment = wdAlignParagraphCenter
       .BoldRun
       .Font.Size = 18
       .TypeText "Sample Word File"
       .BoldRun
       .TypeParagraph
       .Font.Size = 12
       .ParagraphFormat.Alignment = wdAlignParagraphLeft
       .TypeParagraph
       .ParagraphFormat.Alignment = wdAlignParagraphCenter
       .Font.Size = 15
       .TypeText "samples"
   End With

  ActiveDocument.SaveAs2 Filename:="Documents\SampleWord " & Format(Now, "mm-dd-yyyy") & ".docx"

  End With

Label1:

  Set Opfile = Nothing
  Set wrd = Nothing

End Sub

For Each循环下面是我的代码,用于创建Word文档,以防没有打开的具有正确文件名的Word文档。问题是当 For Each 循环运行宏时,它会给出错误

ActiveX component can't create Object

但是当我将其转换为注释并运行创建 Word 文档的代码并取消注释以进行第二次运行测试时,它就可以工作了。我还注意到 Documents.count 不计算打开的 Word 文档。我尝试打开多个 Word 文档,但没有计数。我希望有人能帮忙,谢谢。

最佳答案

我将为您提供很多信息,但不会更改您的代码。如果您能够实现我所解释的内容,您将会学到更多。您的主要问题来自于没有完全掌握使用 GetObjectNew Word.Application 时发生的情况。一旦你完成了排序,你就应该没问题了。

如果 Word 根本没有运行,则 GetObject 将返回您所看到的错误消息。处理该问题的典型方法是测试错误并启动 Word(如有必要),例如

On Error Resume Next
Set wrd = GetObject(, "Word.Application")
If err.number = 429 Then
    Set wrd = new Word.Application
End If
On Error GoTo 0

但是,由于您正在查找特定文档,只要该文档已保存并且您知道文件路径,您就可以(但不必)使用

Dim wrdDoc as Object
Set wrdDoc = GetObject("C:\ExamplePath\DocName.docx")
Set wrd = wrdDoc.Application

也没有必要循环 Documents 集合来获取具有特定名称的文档。您还可以这样做:

Set acFile = wrd.Documents("Filename")

您可以使用测试该文档是否存在

If acFile Is Nothing Then
  'put the code to create a new DOCUMENT here
  Set acFile = wrd.Documents.Add
  'Do all the formatting, etc. here
End If

Documents.Count 的主要问题来自于使用

Set wrd = New Word.Application

每次代码都找不到特定的文档。这会在每次执行时创建一个 Word 的新实例。每个实例都独立于任何其他实例,这就是为什么 Documents.Count 不会返回等于您生成的所有文档的数字。它仅针对当前的 Word 实例运行。

关于VBA:选择事件Word文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50004711/

相关文章:

database - Access 文件对话框导入 - 导入多个 Excel 选项卡/工作表

algorithm - Excel图表平滑算法

sql - 如何解析数据库中每个单元格的特定值?

java - 使用 docx4java 将字段代码插入文档

javascript - 在 Intranet 上打开文档时访问 VBA 中的事件文档

vba - "Type"中的 Const 变量 - 语句 vba

ms-access - 这如何返回一个空值?

vba - 在 Excel 中跟踪 Share-drive 用户名和打开时间?

vba - 差不多好了!如何按整数隐藏行?

excel - Delphi 6 - 从 Delphi 应用程序创建 Excel 图表 - 数据和图表在同一页面上