Runtime error 462 when saving word file from excel

I have an excel sheet that is to create numerous word files while looping through the code. After pasting data från excel, the word files are to be named and saved to the hard drive. The first iteration goes perfect, but on the second I get a Runtime error 462 just before saving the word file.

Any suggestions? Thanks in advance!

Sub Kopiera_Excel_Till_Word(FilVag As String)

Selection.Copy

Dim appWord As Word.Application

Set appWord = New Word.Application

Dim FilNamnVag As String

With appWord

.Visible = True

.Activate

End With

appWord.Documents.Add

appWord.Activate

appWord.Selection.Paste

Application.CutCopyMode = False

With appWord

.Visible = True

.Activate

End With

'****It runs this far the second iteration, then I get Runtime error 462*****

ActiveDocument.SaveAs2 filename:= _
    FilVag, FileFormat:= _
    wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
    :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
    :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
    SaveAsAOCELetter:=False, CompatibilityMode:=15
Application.CutCopyMode = False
ActiveDocument.Close SaveChanges:=False

appWord.Quit

1 answer

  • answered 2022-05-04 15:31 Timothy Rylatt

    When working in VBA it pays to be specific rather than rely on objects such as ActiveDocument

    Sub Kopiera_Excel_Till_Word(FilVag As String)
    
        Selection.Copy
    
        Dim appWord As Word.Application
        Set appWord = New Word.Application
    
        Dim FilNamnVag As String
    
        Dim docWord As Word.Document
        Set docWord = appWord.Documents.Add
    
        docWord.Range.Paste
    
        Application.CutCopyMode = False
    
        docWord.SaveAs2 Filename:= _
            FilVag, FileFormat:= _
            wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles _
            :=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts _
            :=False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
            SaveAsAOCELetter:=False, CompatibilityMode:=15
        docWord.Close SaveChanges:=False
        appWord.Quit
        
        Application.CutCopyMode = False
    End Sub
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum