I recently learned how to manipulate Word documents through VBA in Excel. My problem is I want my macro to be able to determine an active word document with a proper filename and select that document and continue the macro. I have this code below
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
Below the For Each
loop is my code for creating a Word document in case there is no open Word document with the proper filename. The problem is when the For Each
Loop runs the macro it gives the error
ActiveX component can't create Object
But when I turn it into a comment and just run my code that creates a Word document and uncomment it for my second run to test, it works. Also I notice that the Documents.count
doesn't count the open Word documents. I tried opening several Word documents but it doesn't count them. I hope someone can help, thank you.