[英]VBA: selecting an active word document
我最近学习了如何通过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组件无法创建对象
但是,当我将其变成注释并仅运行创建Word文档的代码并取消注释以进行第二次测试时,它就可以工作。 另外,我注意到Documents.count
不计算打开的Word文档。 我尝试打开多个Word文档,但没有算在内。 希望有人能帮助您,谢谢。
我将为您提供很多信息,但不会更改您的代码。 如果可以实施我的解释,您将学到更多。 您的主要问题来自于不完全了解使用GetObject
与New 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的当前实例上运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.