First problem : Run-time error ‘462’ : The remote server machine does not exist or is unavailable.
The issue here is the use of :
- Late Biding :
Dim Smthg As Objector - Implicit references :
Dim Smthg As Rangeinstead of
Dim Smthg As Excel.RangeorDim Smthg As Word.Range
So you need to fully qualified all the variables that you set (I’ve done that in your code)
Second problem
You work with multiple instances of Word and you only need one to handle multiple documents.
So instead of creating a new one each time with :
Set WordApp = CreateObject("Word.Application")
You can get an open instance (if there is one) or create one with that code :
On Error Resume Next
Set WordApp = GetObject(, "Word.Application")
If Err.Number > 0 Then Set WordApp = CreateObject("Word.Application")
On Error GoTo 0
And once you’ve put this at the start of your proc, you can use this instance until the end of the proc and before the end, quit it to avoid having multiple instances running.
Here is your code reviewed and cleaned, take a look :
Sub Docs()
Dim WordApp As Word.Application
Dim WordDoc As Word.Document
' Control if folder exists, if not create folder
If Len(Dir("F:documents" & Year(Date), vbDirectory)) = 0 Then MkDir "F:documents" & Year(Date)
' Get or Create a Word Instance
On Error Resume Next
Set WordApp = GetObject(, "Word.Application")
If Err.Number > 0 Then Set WordApp = CreateObject("Word.Application")
On Error GoTo 0
Workbooks("exampleworkbook.xlsm").Sheets("examplesheet").Range("A1:C33").Copy
With WordApp
.Visible = True
.Activate
Set WordDoc = .Documents.Add
.Selection.PasteSpecial Link:=False, DataType:=wdPasteRTF, _
Placement:=wdInLine, DisplayAsIcon:=False
End With
With Application
.Wait (Now + TimeValue("0:00:02"))
.CutCopyMode = False
End With
With WordDoc
.PageSetup.TopMargin = WordApp.CentimetersToPoints(1.4)
.PageSetup.LeftMargin = WordApp.CentimetersToPoints(1.5)
.PageSetup.BottomMargin = WordApp.CentimetersToPoints(1.5)
.SaveAs "F:documents" & Year(Date) & "examplename " & Format(Now, "YYYYMMDD") & ".docx"
.Close
End With
' export sheet 2 to Word
Workbooks("exampleworkbook.xlsm").Sheets("examplesheet2").Range("A1:C33").Copy
Set WordDoc = WordApp.Documents.Add
WordApp.Selection.PasteSpecial Link:=False, DataType:=wdPasteRTF, _
Placement:=wdInLine, DisplayAsIcon:=False
Application.Wait (Now + TimeValue("0:00:02"))
With WordDoc
.PageSetup.LeftMargin = WordApp.CentimetersToPoints(1.5)
.PageSetup.TopMargin = WordApp.CentimetersToPoints(1.4)
.PageSetup.BottomMargin = WordApp.CentimetersToPoints(1.5)
.SaveAs "F:files" & Year(Date) & "name" & Format(Now, "YYYYMMDD") & ".docx"
.Close
End With
Application.CutCopyMode = False
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
' Variables Outlook
Dim objOutlook As Outlook.Application
Dim objMail As Outlook.MailItem
Dim rngTo As Excel.Range
Dim rngCc As Excel.Range
Dim rngSubject As Excel.Range
Dim rngBody As Excel.Range
Dim rngAttach1 As Excel.Range
Dim rngAttach2 As Excel.Range
Dim numSend As Integer
On Error Resume Next
Set objOutlook = GetObject(, "Outlook.Application")
If Err.Number > 0 Then Set objOutlook = CreateObject("Outlook.Application")
On Error GoTo 0
Set objMail = objOutlook.CreateItem(0)
' Outlook
On Error GoTo handleError
With Sheets("Mail")
Set rngTo = .Range("B11")
Set rngCc = .Range("B12")
Set rngSubject = .Range("B13")
Set rngBody = .Range("B14")
Set rngAttach1 = .Range("B15")
Set rngAttach2 = .Range("B16")
End With
With objMail
.To = rngTo.Value
.Subject = rngSubject.Value
.CC = rngCc.Value
'.Body = rngBody.Value
.Body = "Hi," & _
vbNewLine & vbNewLine & _
rngBody.Value & _
vbNewLine & vbNewLine & _
"Kind regards,"
.Attachments.Add rngAttach1.Value
.Attachments.Add rngAttach2.Value
.Display
Application.Wait (Now + TimeValue("0:00:01"))
Application.SendKeys "%s"
' .Send ' Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
End With
numSend = numSend + 1
GoTo skipError
handleError:
numErr = numErr + 1
oFile.WriteLine "*** ERROR *** Email for account" & broker & " not sent. Error: " & Err.Number & " " & Err.Description
skipError:
On Error GoTo 0
MsgBox "Sent emails: " & numSend & vbNewLine & "Number of errors: " & numErr, vbOKOnly + vbInformation, "Operation finished"
GoTo endProgram
cancelProgram:
MsgBox "No mails were sent.", vbOKOnly + vbExclamation, "Operation cancelled"
endProgram:
Set objOutlook = Nothing
Set objMail = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing
Set rngAttach1 = Nothing
Set rngAttach2 = Nothing
End Sub
I occasionally get a run time error when trying to open/manipulate Excel files using Access VBA. The error is
«Run-Time error ‘462’: The remote server machine does not exist or is
unavailable
What is frustrating is that the error occurs only for certain files and not others and in different instances. Here is my code, the error occurs at the workbooks.open(sPath) line:
DoCmd.SetWarnings False
Dim oExcel As New Excel.Application
Dim oWB As Workbook
Dim oWS As Worksheet
Set oExcel = Excel.Application
Set oWB = oExcel.Workbooks.Open(sPath)
Set oWS = oWB.Sheets(1)
oExcel.Visible = False
If fGetFileName(sPath) = "FILE_NAME1.xlsx" Then
'oExcel.Visible = False
oWS.Range("AW1").Value = "TEXT1"
oWS.Range("AX1").Value = "TEXT2"
oWS.Range("AY1").Value = "TEXT3"
End If
oWB.Save
Debug.Print "Amended " & sPath
oWB.Close False
Set oWB = Nothing
oExcel.Quit
Set oExcel = Nothing
DoCmd.SetWarnings True
After a bit of research online, I’ve found this document gives a good overview of the error: https://anictteacher.files.wordpress.com/2011/11/vba-error-462-explained-and-resolved.pdf
Using the logic from that document, the error is that:
object has not been fully qualified by reference to the Office object
in every case
However, I amended the row where the error occurs to specifically reference the Excel object (Set oWB = oExcel.Workbooks.Open(sPath)). Have tried declaring the dimensions as Objects and put reference to oExcel in every mention of a workbook/sheet. Any ideas? Does sPath need to better qualified?
Permalink
Cannot retrieve contributors at this time
| title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
|---|---|---|---|---|---|---|
|
The remote server machine does not exist or is unavailable (Error 462) |
vblr6.chm1000462 |
vblr6.chm1000462 |
office |
b7a74e81-f700-a278-2f83-8faed4dd069f |
06/08/2017 |
medium |
The CreateObject function requires a valid server. This error has the following cause and solution:
- A server parameter was specified, but the server could not be either reached or found.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
- Remove From My Forums
-
Question
-
I get the above error when i run the code bellow , but when i re-run it after the error occur, the code seems to Work fine. For sure im missing something in it. Can you point
me the right way to do this?I have a main form with two sub forms one of the sub forms contains a list of several OLE selected word documents, in which I loop, passing all these documents to another sub
form, which also contains an OLE Field, which will gather these Documents, in one.First Sub: Private Sub Command54_Click() Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Verb = acOLEVerbOpen Forms!frmFScomposicao!subfrmKitCenas![FSKitCenasOLE].Verb = acOLEVerbOpen Set GeraKit0 = Forms!frmFScomposicao!subfrmKitCenas!FSKitCenasOLE.Range With GeraKit0.Select GeraKit0.WholeStory GeraKit0.Delete End With Dim FirstTime As Integer FirstTime = 1 Me.FirstTimeBox = FirstTime Forms!frmFScomposicao!PRODUCAO.SetFocus DoCmd.RunCommand acCmdRecordsGoToFirst For f = 1 To Forms!frmFScomposicao!PRODUCAO![Tiroliro] Me.FirstTimeBox = FirstTime Call CompilarKitDiaGravacao Forms!frmFScomposicao!PRODUCAO.SetFocus FirstTime = FirstTime + 1 DoCmd.RunCommand acCmdRecordsGoToNext Next f DoCmd.RunCommand acCmdRecordsGoToFirst End Sub Second Sub: Public Sub CompilarKitDiaGravacao() 'Set cenaspararecolher = Forms!frmFScomposicao!PRODUCAO.Action = acOLEActivate Set cenaspararecolher = Forms!frmFScomposicao!PRODUCAO![Prod_Cena_Guiao].Range With cenaspararecolher.Select cenaspararecolher.WholeStory cenaspararecolher.Copy Set cenaspararecolher = Nothing End With If Forms!frmFScomposicao.FirstTimeBox = 1 Then Set Vinho = Forms!frmFScomposicao!subfrmKitCenas!FSKitCenasOLE.Range With Vinho.Select Selection.EndKey wdStory Selection.InsertBreak Type:=wdSectionBreakContinuous Selection.PasteAndFormat wdPasteDefault End With Forms!frmFScomposicao!FirstTimeBox = Forms!frmFScomposicao!FirstTimeBox + 1 Else Set Vinho = Forms!frmFScomposicao!subfrmKitCenas!FSKitCenasOLE.Range With Vinho.Select Selection.EndKey wdStory Selection.InsertBreak 'Type:=wdSectionBreakContinuous Selection.PasteAndFormat wdPasteDefault End With End If End Sub
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 |
Private Function funOutputWord(strPathDot As String, strPathWord As String, arr_data As Variant, cnt_rows As Variant) As Boolean ' '-------------------------------------------------------------------------- Dim objWord As Word.Application Dim objDoc As Word.Document Dim DlgUser As Integer Dim myTable As Word.Table Dim objRange As Object On Error GoTo 0 Set objWord = New Word.Application If Dir(strPathWord) <> "" Then DlgUser = MsgBox("Документ с таким именем ранее уже был создан. Заменить его?", vbYesNo, "admin") Select Case DlgUser Case vbNo objWord.Documents.Open strPathWord GoTo funOutputWord_End Case Else Kill strPathWord End Select End If 'Открываем НОВЫЙ документ сформированный по заданному шаблону Set objDoc = objWord.Documents.Add(strPathDot) Set myTable = objWord.Selection.Range.Tables.Add(objDoc.Bookmarks("таблица").Range, cnt_rows, 6) With myTable .AutoFormat 16 .Columns(1).Width = CentimetersToPoints(1.19) .Columns(2).Width = CentimetersToPoints(2.75) .Columns(3).Width = CentimetersToPoints(2.25) .Columns(4).Width = CentimetersToPoints(6.75) .Columns(5).Width = CentimetersToPoints(3) .Columns(6).Width = CentimetersToPoints(2.79) For i = 1 To 6 myTable.Cell(1, i).Range.ParagraphFormat.Alignment = 1 myTable.Cell(1, i).Range.Cells.VerticalAlignment = 1 ' строка заголовков - жирным myTable.Cell(1, i).Range.Bold = True Next i myTable.Cell(1, 1).Range.Text = "№ п/п" myTable.Cell(1, 2).Range.Text = "Столбик 2" myTable.Cell(1, 3).Range.Text = "Столбик 3" myTable.Cell(1, 4).Range.Text = "Столбик 4" myTable.Cell(1, 5).Range.Text = "Столбик 5" myTable.Cell(1, 6).Range.Text = "Столбик 6" For i = 1 To UBound(arr_data) For j = 0 To UBound(arr_data, 2) If i = 1 Then myTable.Cell(j + 2, i).Range.Text = arr_data(i, j) & "." Else myTable.Cell(j + 2, i).Range.Text = arr_data(i, j) End If Select Case i Case 1, 4, 5, 6 ' от левого myTable.Cell(j + 2, i).Range.ParagraphFormat.Alignment = 0 Case 2 ' центр myTable.Cell(j + 2, i).Range.ParagraphFormat.Alignment = 1 Case 3 ' от правого myTable.Cell(j + 2, i).Range.ParagraphFormat.Alignment = 2 End Select myTable.Cell(j + 2, i).Range.Cells.VerticalAlignment = 1 Next j Next i '.SaveAs strPathWord End With funOutputWord = True funOutputWord_End: On Error Resume Next objWord.Visible = True objWord.Activate Set myTable = Nothing Set objRange = Nothing Set objDoc = Nothing Set objWord = Nothing Err.Clear Exit Function funOutputWord_Err: funOutputWord = False MsgBox "Error: " & Err.Number & vbCrLf & Err.Description & vbCrLf & _ "in Function: funOutputWord in module: Form_Form1", vbCritical, "Error in Application" Err.Clear Resume funOutputWord_End End Function |
