YasserKhalil
Well-Known Member
Hello everyone
I have this code that would export excel range to word
It works well for first running but when executing it for a second time I encountered an error
(The remote server machine doesn't exist or is unavailable)
Hope to find solution
I have this code that would export excel range to word
It works well for first running but when executing it for a second time I encountered an error
(The remote server machine doesn't exist or is unavailable)
Code:
Sub SaveToWord()
Dim S_ALI$
Dim SAV_ALI As String
Dim tbl As Excel.Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Application.ScreenUpdating = False
Application.EnableEvents = False
SAV_ALI = ThisWorkbook.Path & "\" & ActiveSheet.Name & "\"
S_ALI = Range("C3") & ".docx"
Set tbl = ActiveSheet.Range(ActiveSheet.PageSetup.PrintArea)
On Error Resume Next
Set WordApp = GetObject(class:="Word.Application")
Err.Clear
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
WordApp.Visible = True
WordApp.WindowState = wdWindowStateMinimize
Set myDoc = WordApp.Documents.Add
tbl.Copy
myDoc.Paragraphs(1).Range.PasteExcelTable LinkedToExcel:=False, WordFormatting:=False, RTF:=False
With ActiveDocument.PageSetup
.LineNumbering.Active = False
.TopMargin = CentimetersToPoints(1)
.BottomMargin = CentimetersToPoints(1)
.LeftMargin = CentimetersToPoints(1)
.RightMargin = CentimetersToPoints(1)
End With
Set WordTable = myDoc.Tables(1)
WordTable.AutoFitBehavior (wdAutoFitWindow)
With ActiveDocument
On Error Resume Next
MkDir SAV_ALI
ActiveDocument.SaveAs SAV_ALI & ActiveSheet.Name & " " & S_ALI
End With
With WordApp
.ActiveDocument.Close
.Quit
End With
Set WordApp = Nothing
EndRoutine:
Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub