Error 462 excel

Все доброй ночи!     Очень извиняюсь, что касаюсь избитой темы (наверное), но что-то я не смог найти ответа в таком форуме, хотя регулярно пользуюсь подсказками пользователей. До сей поры хватало.     Суть вот в чем:   Я хочу из существующей таблицы Excel выдернуть отсортированные значения и вставить их в Word. Казалось бы, что может быть проще:     Sub Import2()   '   '     '      Mesyats = UserForm1.ComboBox1.Value    ...

Все доброй ночи!  

  Очень извиняюсь, что касаюсь избитой темы (наверное), но что-то я не смог найти ответа в таком форуме, хотя регулярно пользуюсь подсказками пользователей. До сей поры хватало.  

  Суть вот в чем:  
Я хочу из существующей таблицы Excel выдернуть отсортированные значения и вставить их в Word. Казалось бы, что может быть проще:  

  Sub Import2()  
‘  
‘  

  ‘  
   Mesyats = UserForm1.ComboBox1.Value  
   ‘Mesyats = «Ноябрь»  
   Dim iLastRow As Long  
   Excel.Sheets(«123»).Select  
   iLastRow = Cells(Rows.Count, 1).End(xlUp).Row  
   Excel.ActiveSheet.ListObjects(«Таблица 3»).Range.AutoFilter Field:=1, Criteria1:=Mesyats  
   Excel.Range(«B3:D» + Right((Str(iLastRow)), (Len(Str(iLastRow) — 1)))).Select  
   Excel.Selection.Copy  
   Excel.Sheets(«123»).Select  
   On Error GoTo ErrStartWord  
   Dim Wda As Word.Application  
   Set Wda = GetObject(, «Word.Application»)  
   Set Wda = Nothing  
   ‘If Tasks.Exists(«Microsoft Word») Then  
   ‘End If  
   ‘Word.Application.Documents.Item  
   Word.Documents.Open Filename:=»c:OLS ReportsForm 2.docx»  
   Word.Application.Activate  
   Word.Selection.StartOf Unit:=wdStory, Extend:=wdMove  
   Word.Selection.MoveDown Unit:=wdLine, Count:=9  
   Word.Selection.MoveLeft Unit:=wdCharacter, Count:=17  
   Word.Selection.Delete Unit:=wdCharacter, Count:=7  
   Word.Selection.TypeText (Mesyats)  
   Word.Selection.MoveEnd  
   Word.Selection.MoveDown Unit:=wdLine, Count:=6  
   Word.Selection.MoveLeft Unit:=wdCharacter, Count:=1  
   WordBasic.EditPaste2  
   ‘Word.Application.Dialogs(wdDialogFileSaveAs).Show  
   ‘Word.Documents.Close  
ErrStartWord:  
   If Err.Number = 429 Then ‘ Word не запущен  
    Dim appWD As Object  
    Set appWD = CreateObject(«Word.Application»)  
    appWD.Visible = True  
    Resume Next  
   End If  
     If Err.Number = 0 Then  
      ‘MsgBox «Success!»  
     Else: MsgBox Err.Description & » » & Err.Number, vblnformation  
     End If  
End Sub  

  Однако не тут-то было (((    

  При повторном запуске скрипт срубается на строке «Word.Documents.Open Filename:=»c:OLS ReportsForm 2.docx»»  

  с сообщением «The remote server machine does not exist or is unavailable 462», как и положено обработчику ошибок в теле сркипта. Надо полностью закрыть Excel и заново в него зайти. Тогда вновь все заработает, на 1 раз :/ Я так думаю, что скрипт по завершению не очищает какие-то переменные, и нужно выйти из Excel.    

  Очень надо сделать, работа горит. Сижу уже 4-й час, и ничего не могу поделать ((((  

  И да. Использую Word 2007 и Excel 2007. Как думаете, в 2003 офисе такой проблемы не возникнет? А то будет жаль перставлять из-за этого…..    

  Все харанее спасибо.

Icon Ex Номер ошибки: Ошибка 462
Название ошибки: Excel Error 462
Описание ошибки: Ошибка 462: Возникла ошибка в приложении Microsoft Excel. Приложение будет закрыто. Приносим извинения за неудобства.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Excel
Относится к: Windows XP, Vista, 7, 8, 10, 11

Анализ «Excel Error 462»

«Excel Error 462» — это стандартная ошибка времени выполнения. Разработчики тратят много времени и усилий на написание кода, чтобы убедиться, что Microsoft Excel стабилен до продажи продукта. К сожалению, некоторые критические проблемы, такие как ошибка 462, часто могут быть упущены из виду.

После установки программного обеспечения может появиться сообщение об ошибке «Excel Error 462». В случае обнаруженной ошибки 462 клиенты могут сообщить о наличии проблемы Microsoft Corporation по электронной почте или сообщать об ошибках. Затем Microsoft Corporation нужно будет исправить эти ошибки в главном исходном коде и предоставить модифицированную версию для загрузки. Эта ситуация происходит из-за обновления программного обеспечения Microsoft Excel является одним из решений ошибок 462 ошибок и других проблем.

Почему возникает ошибка времени выполнения 462?

У вас будет сбой во время выполнения Microsoft Excel, если вы столкнетесь с «Excel Error 462» во время выполнения. Причины сбоев обработки можно отличить, классифицируя ошибки 462 следующим образом:.

Ошибка 462 Crash — это типичная ошибка 462 во время выполнения, которая полностью аварийно завершает работу компьютера. Эти ошибки обычно возникают, когда входы Microsoft Excel не могут быть правильно обработаны, или они смущены тем, что должно быть выведено.

«Excel Error 462» Утечка памяти — Ошибка 462 утечка памяти происходит и предоставляет Microsoft Excel в качестве виновника, перетаскивая производительность вашего ПК. Возможные искры включают сбой освобождения, который произошел в программе, отличной от C ++, когда поврежденный код сборки неправильно выполняет бесконечный цикл.

Ошибка 462 Logic Error — Логическая ошибка вызывает неправильный вывод, даже если пользователь дал действительные входные данные. Когда точность исходного кода Microsoft Corporation низкая, он обычно становится источником ошибок.

Excel Error 462 проблемы часто являются результатом отсутствия, удаления или случайного перемещения файла из исходного места установки Microsoft Excel. Как правило, самый лучший и простой способ устранения ошибок, связанных с файлами Microsoft Corporation, является замена файлов. Если ошибка Excel Error 462 возникла в результате его удаления по причине заражения вредоносным ПО, мы рекомендуем запустить сканирование реестра, чтобы очистить все недействительные ссылки на пути к файлам, созданные вредоносной программой.

Распространенные проблемы Excel Error 462

Типичные ошибки Excel Error 462, возникающие в Microsoft Excel для Windows:

  • «Ошибка программы Excel Error 462. «
  • «Excel Error 462 не является приложением Win32.»
  • «Возникла ошибка в приложении Excel Error 462. Приложение будет закрыто. Приносим извинения за неудобства.»
  • «К сожалению, мы не можем найти Excel Error 462. «
  • «Excel Error 462 не может быть найден. «
  • «Ошибка запуска программы: Excel Error 462.»
  • «Excel Error 462 не выполняется. «
  • «Excel Error 462 остановлен. «
  • «Excel Error 462: путь приложения является ошибкой. «

Проблемы Excel Error 462 с участием Microsoft Excels возникают во время установки, при запуске или завершении работы программного обеспечения, связанного с Excel Error 462, или во время процесса установки Windows. При появлении ошибки Excel Error 462 запишите вхождения для устранения неполадок Microsoft Excel и чтобы HelpMicrosoft Corporation найти причину.

Excel Error 462 Истоки проблем

Проблемы Excel Error 462 могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Excel Error 462, или к вирусам / вредоносному ПО.

Особенно ошибки Excel Error 462 проистекают из:

  • Поврежденная или недопустимая запись реестра Excel Error 462.
  • Загрязненный вирусом и поврежденный Excel Error 462.
  • Другая программа злонамеренно или по ошибке удалила файлы, связанные с Excel Error 462.
  • Другая программа находится в конфликте с Microsoft Excel и его общими файлами ссылок.
  • Microsoft Excel/Excel Error 462 поврежден от неполной загрузки или установки.

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

First problem : Run-time error ‘462’ : The remote server machine does not exist or is unavailable.

The issue here is the use of :

  1. Late Biding : Dim Smthg As Object or
  2. Implicit references : Dim Smthg As Range instead of
    Dim Smthg As Excel.Range or Dim 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

В этой статье представлена ошибка с номером Ошибка 462, известная как Ошибка Excel 462, описанная как Ошибка 462: Возникла ошибка в приложении Microsoft Excel. Приложение будет закрыто. Приносим свои извинения за неудобства.

О программе Runtime Ошибка 462

Время выполнения Ошибка 462 происходит, когда Microsoft Excel дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.

Определения (Бета)

Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!

  • Excel — только для вопросов по программированию с объектами или файлами Excel или по разработке сложных формул.

Симптомы Ошибка 462 — Ошибка Excel 462

Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.

Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.

Fix Ошибка Excel 462 (Error Ошибка 462)
(Только для примера)

Причины Ошибка Excel 462 — Ошибка 462

При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.

Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.

Методы исправления

Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.

Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.

Обратите внимание: ни ErrorVault.com, ни его авторы не несут ответственности за результаты действий, предпринятых при использовании любого из методов ремонта, перечисленных на этой странице — вы выполняете эти шаги на свой страх и риск.

Метод 1 — Закройте конфликтующие программы

Когда вы получаете ошибку во время выполнения, имейте в виду, что это происходит из-за программ, которые конфликтуют друг с другом. Первое, что вы можете сделать, чтобы решить проблему, — это остановить эти конфликтующие программы.

  • Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
  • Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
  • Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
  • Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.

Метод 2 — Обновите / переустановите конфликтующие программы

Использование панели управления

  • В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
  • В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
  • Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
  • В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
  • Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.

Использование других методов

  • В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
  • В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
  • Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
  • Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.

Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.

Заражение вирусом, вызывающее ошибку выполнения на вашем компьютере, необходимо немедленно предотвратить, поместить в карантин или удалить. Убедитесь, что вы обновили свою антивирусную программу и выполнили тщательное сканирование компьютера или запустите Центр обновления Windows, чтобы получить последние определения вирусов и исправить их.

Метод 4 — Переустановите библиотеки времени выполнения

Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.

  • Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
  • Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
  • Загрузите последний распространяемый пакет от Microsoft и установите его.

Метод 5 — Запустить очистку диска

Вы также можете столкнуться с ошибкой выполнения из-за очень нехватки свободного места на вашем компьютере.

  • Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
  • Вы также можете очистить кеш и перезагрузить компьютер.
  • Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C :)
  • Щелкните «Свойства», а затем — «Очистка диска».

Метод 6 — Переустановите графический драйвер

Если ошибка связана с плохим графическим драйвером, вы можете сделать следующее:

  • Откройте диспетчер устройств и найдите драйвер видеокарты.
  • Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.

Метод 7 — Ошибка выполнения, связанная с IE

Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:

  1. Сбросьте настройки браузера.
    • В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
    • Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
  2. Отключить отладку скриптов и уведомления об ошибках.
    • В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
    • Установите флажок в переключателе.
    • Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.

Если эти быстрые исправления не работают, вы всегда можете сделать резервную копию файлов и запустить восстановление на вашем компьютере. Однако вы можете сделать это позже, когда перечисленные здесь решения не сработают.

Другие языки:

How to fix Error 462 (Excel Error 462) — Error 462: Microsoft Excel has encountered a problem and needs to close. We are sorry for the inconvenience.
Wie beheben Fehler 462 (Excel-Fehler 462) — Fehler 462: Microsoft Excel hat ein Problem festgestellt und muss geschlossen werden. Wir entschuldigen uns für die Unannehmlichkeiten.
Come fissare Errore 462 (Errore di Excel 462) — Errore 462: Microsoft Excel ha riscontrato un problema e deve essere chiuso. Ci scusiamo per l’inconveniente.
Hoe maak je Fout 462 (Excel-fout 462) — Fout 462: Microsoft Excel heeft een probleem ondervonden en moet worden afgesloten. Excuses voor het ongemak.
Comment réparer Erreur 462 (Erreur Excel 462) — Erreur 462 : Microsoft Excel a rencontré un problème et doit se fermer. Nous sommes désolés du dérangement.
어떻게 고치는 지 오류 462 (엑셀 오류 462) — 오류 462: Microsoft Excel에 문제가 발생해 닫아야 합니다. 불편을 끼쳐드려 죄송합니다.
Como corrigir o Erro 462 (Erro do Excel 462) — Erro 462: O Microsoft Excel encontrou um problema e precisa fechar. Lamentamos o inconveniente.
Hur man åtgärdar Fel 462 (Excel-fel 462) — Fel 462: Microsoft Excel har stött på ett problem och måste avslutas. Vi är ledsna för besväret.
Jak naprawić Błąd 462 (Błąd Excela 462) — Błąd 462: Microsoft Excel napotkał problem i musi zostać zamknięty. Przepraszamy za niedogodności.
Cómo arreglar Error 462 (Error de Excel 462) — Error 462: Microsoft Excel ha detectado un problema y debe cerrarse. Lamentamos las molestias.

The Author Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.

Следуйте за нами: Facebook Youtube Twitter

Рекомендуемый инструмент для ремонта:

Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.

ШАГ 1:

Нажмите здесь, чтобы скачать и установите средство восстановления Windows.

ШАГ 2:

Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.

ШАГ 3:

Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.

СКАЧАТЬ СЕЙЧАС

Совместимость

Требования

1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.

ID статьи: ACX04265RU

Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

Содержание

  1. Excel automation fails second time code runs
  2. Symptoms
  3. Cause
  4. Resolution
  5. Status
  6. More Information
  7. Steps to reproduce the behavior
  8. References
  9. Excel automation fails second time code runs
  10. Symptoms
  11. Cause
  12. Resolution
  13. Status
  14. More Information
  15. Steps to reproduce the behavior
  16. References
  17. Thread: RESOLVED: [VBA Word/Excel] Error 462 when running the code twice
  18. RESOLVED: [VBA Word/Excel] Error 462 when running the code twice
  19. Vba excel run time error 462

Excel automation fails second time code runs

Symptoms

While running code that uses Automation to control Microsoft Excel, one of the following errors may occur:

In Microsoft Excel 97 and in later versions of Excel, you receive one of the following error message:

Error message 1

Run-time error ‘1004’:
Method ‘ ‘ of object ‘_Global’ failed

Error message 2

Application-defined or object-defined error

In Microsoft Excel 95, you receive one of the following error messages:

Error message 1

Run-time error ‘-2147023174’
OLE Automation error

Error message 2

Run-time error ‘462’:
The remote server machine does not exist or is unavailable.

Cause

Visual Basic has established a reference to Excel because of a line of code that calls an Excel object, method, or property without qualifying the element with an Excel object variable. Visual Basic does not release this reference until you end the program. This errant reference interferes with automation code when the code is run more than one time.

Resolution

To resolve this problem, modify the code so each call to an Excel object, method, or property is qualified with the appropriate object variable.

Status

This behavior is by design.

More Information

To automate Microsoft Excel, you establish an object variable that usually refers to the Excel Application object or the Excel Workbook object. Other object variables can then be set to refer to a Worksheet, a Range, or other objects in the Microsoft Excel object model. When you write code to use an Excel object, method, or property, you should always precede the call with the appropriate object variable. If you do not, Visual Basic establishes its own reference to Excel. This reference might cause problems when you try to run the automation code multiple times. Note that even if the line of code begins with the object variable, a call may be made to an Excel object, method, or property in the middle of the line of code that is not preceded with an object variable.

The following steps illustrate how to reproduce this issue and how to correct the issue.

Steps to reproduce the behavior

Start a new Standard EXE project in Visual Basic. Form1 is created by default.

On the Project menu, click References, and then check the Object Library for the version of Excel that you intend to automate.

Place a CommandButton control on Form1.

Copy the following code example to the Code Window of Form1.

On the Run menu, click Start, or press F5 to start the program.

Click the CommandButton control. No error occurs. However, a reference to Excel has been created and has not been released.

Click the CommandButton control again. Notice that you receive one of the error messages that are discussed in the «Symptoms» section.

Note The error message occurs because the code refers to the method of the cell without preceding the call with the
xlSheet object variable.

Stop the project and change the following line of code:

Change the line of code to resemble the following line of code.

Run the program again. Notice that you can run the code multiple times without receiving an error message.

References

For more information, click the following article numbers to view the articles in the Microsoft Knowledge Base:

167223 Microsoft Office 97 Automation Help file available

189618 You may receive the «Run-time error ‘-2147023174’ (800706ba)» error message or the «Run-time error ‘462’» when you run Visual Basic code that uses Automation to control Word

Источник

Excel automation fails second time code runs

Symptoms

While running code that uses Automation to control Microsoft Excel, one of the following errors may occur:

In Microsoft Excel 97 and in later versions of Excel, you receive one of the following error message:

Error message 1

Run-time error ‘1004’:
Method ‘ ‘ of object ‘_Global’ failed

Error message 2

Application-defined or object-defined error

In Microsoft Excel 95, you receive one of the following error messages:

Error message 1

Run-time error ‘-2147023174’
OLE Automation error

Error message 2

Run-time error ‘462’:
The remote server machine does not exist or is unavailable.

Cause

Visual Basic has established a reference to Excel because of a line of code that calls an Excel object, method, or property without qualifying the element with an Excel object variable. Visual Basic does not release this reference until you end the program. This errant reference interferes with automation code when the code is run more than one time.

Resolution

To resolve this problem, modify the code so each call to an Excel object, method, or property is qualified with the appropriate object variable.

Status

This behavior is by design.

More Information

To automate Microsoft Excel, you establish an object variable that usually refers to the Excel Application object or the Excel Workbook object. Other object variables can then be set to refer to a Worksheet, a Range, or other objects in the Microsoft Excel object model. When you write code to use an Excel object, method, or property, you should always precede the call with the appropriate object variable. If you do not, Visual Basic establishes its own reference to Excel. This reference might cause problems when you try to run the automation code multiple times. Note that even if the line of code begins with the object variable, a call may be made to an Excel object, method, or property in the middle of the line of code that is not preceded with an object variable.

The following steps illustrate how to reproduce this issue and how to correct the issue.

Steps to reproduce the behavior

Start a new Standard EXE project in Visual Basic. Form1 is created by default.

On the Project menu, click References, and then check the Object Library for the version of Excel that you intend to automate.

Place a CommandButton control on Form1.

Copy the following code example to the Code Window of Form1.

On the Run menu, click Start, or press F5 to start the program.

Click the CommandButton control. No error occurs. However, a reference to Excel has been created and has not been released.

Click the CommandButton control again. Notice that you receive one of the error messages that are discussed in the «Symptoms» section.

Note The error message occurs because the code refers to the method of the cell without preceding the call with the
xlSheet object variable.

Stop the project and change the following line of code:

Change the line of code to resemble the following line of code.

Run the program again. Notice that you can run the code multiple times without receiving an error message.

References

For more information, click the following article numbers to view the articles in the Microsoft Knowledge Base:

167223 Microsoft Office 97 Automation Help file available

189618 You may receive the «Run-time error ‘-2147023174’ (800706ba)» error message or the «Run-time error ‘462’» when you run Visual Basic code that uses Automation to control Word

Источник

Thread: RESOLVED: [VBA Word/Excel] Error 462 when running the code twice

Thread Tools
Display

RESOLVED: [VBA Word/Excel] Error 462 when running the code twice

Hi, this is my first post, so if I’ve done something wrong like forgotten code tags or posted in the wrong section, please don’t yell at me

Before I explain the problem, I want to say that I am aware other people have posted this same problem, even on this website, but the solutions that seem to be working for everyone else have not worked for me. I have researched this problem for some 5 hours now and spent days trying to resolve it. Some examples of other threads that I have read with the same issue:

The issue is that I am writing code in VBA Word which calls an instance of Excel, does some stuff, and then closes Excel. Running the code again a second time usually results in the infamous error 462: «The remote server machine does not exist or is unavailable».

The Microsoft knowledge base (link above) advises to «Modify the code so that each call to a Word object, method, or property is qualified with the appropriate object variable.» I have gone through with a fine tooth comb and made sure that everything is qualified and referenced correctly and explicitly.

Furthermore, after reading the second article (link above) I have used late-binding on their suggestion to remove the issue of the Excel application continuing to run in the background after its supposed to be closed. I have found the [first instance of] offending line which causes the Excel app to continue to run, which, if omitted, makes the problem go away.

The code is quite lengthy so I will only post the relevant parts:

The code in red is where the error message appears when it is run a second time. However, it seems that Excel is reference properly here, so no idea why this is occurring. I have tried the following variations with no success:

Note that the above code is not resolving the original error of having the Excel app continuing to run in the background. I am in the middle of trying to fix this when I started getting the Error 462. To isolate the latter, add an early exit like:

Hope this makes sense, and hope someone can help, because I am at the end of my tether.

Last edited by Earlien; Jan 3rd, 2012 at 07:22 PM . Reason: Problem resolved

Источник

Vba excel run time error 462

Модератор форума: китин, _Boroda_

Мир MS Excel » Вопросы и решения » Вопросы по VBA » Макрос по созданию файла MS WORD. run-time error 462 (Макросы/Sub)

Макрос по созданию файла MS WORD. run-time error 462

rvshestakov Дата: Четверг, 19.03.2015, 16:35 | Сообщение № 1

Добрый день всем!
Заметил странную особенность, если не сказать больше.
Если при выполнении макроса по созданию файла MS WORD в диспетчере задач WINDOWS нет процесса WINWORD.EXE — выполнение макроса прерывается ошибкой run-time error 462.
Причём при нажатии кнопки debug подсвечивается строка с форматированием листа создаваемого файла — ParagraphFormat.LeftIndent = CentimetersToPoints(0).

Если процесс WINWORD.EXE активен — код работает исправно.
Код макроса прикладывать пока не буду. Если потребуется, приложу.
Заранее спасибо!

Добрый день всем!
Заметил странную особенность, если не сказать больше.
Если при выполнении макроса по созданию файла MS WORD в диспетчере задач WINDOWS нет процесса WINWORD.EXE — выполнение макроса прерывается ошибкой run-time error 462.
Причём при нажатии кнопки debug подсвечивается строка с форматированием листа создаваемого файла — ParagraphFormat.LeftIndent = CentimetersToPoints(0).

Если процесс WINWORD.EXE активен — код работает исправно.
Код макроса прикладывать пока не буду. Если потребуется, приложу.
Заранее спасибо! rvshestakov

Сообщение Добрый день всем!
Заметил странную особенность, если не сказать больше.
Если при выполнении макроса по созданию файла MS WORD в диспетчере задач WINDOWS нет процесса WINWORD.EXE — выполнение макроса прерывается ошибкой run-time error 462.
Причём при нажатии кнопки debug подсвечивается строка с форматированием листа создаваемого файла — ParagraphFormat.LeftIndent = CentimetersToPoints(0).

Если процесс WINWORD.EXE активен — код работает исправно.
Код макроса прикладывать пока не буду. Если потребуется, приложу.
Заранее спасибо! Автор — rvshestakov
Дата добавления — 19.03.2015 в 16:35

doober Дата: Четверг, 19.03.2015, 17:22 | Сообщение № 2
rvshestakov Дата: Пятница, 20.03.2015, 06:36 | Сообщение № 3

doober,
просто в моём случае ошибка может быть очевидной, поэтому я подумал, что возможно и не в коде дело и моя ошибка лежит на поверхности

200?’200px’:»+(this.scrollHeight+5)+’px’);»> Dim PathForFile As String
Dim NameWRD As String
Set AppWord = CreateObject(«Word.Application»)
NameWRD = Sheets(1).Range(«НомерЗакупки»).Value & «. Проект решения » & Sheets(1).Range(«ТипПрезентации»).Value & «.docx»
PathForFile$ = ThisWorkbook.Path
Set FSO = CreateObject(«Scripting.FileSystemObject»)
If Not FSO.FolderExists(PathForFile$) Then
FSO.CreateFolder (PathForFile$) ‘
End If
Set FSO = Nothing

AppWord.Documents.Add
AppWord.Selection.Paste
AppWord.Selection.WholeStory
If AppWord.Selection.PageSetup.Orientation = wdOrientPortrait Then
AppWord.Selection.PageSetup.Orientation = wdOrientLandscape
Else
AppWord.Selection.PageSetup.Orientation = wdOrientPortrait
End If
With AppWord.Selection.ParagraphFormat
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineUnitBefore = 0
.LineUnitAfter = 0
.LeftIndent = CentimetersToPoints(0)
.SpaceBeforeAuto = False
.SpaceAfterAuto = False
.SpaceBeforeAuto = False
.SpaceAfterAuto = False
.FirstLineIndent = CentimetersToPoints(0)
End With
With AppWord.Selection
.Font.Name = «Times New Roman»
‘ .Font.Size = 14
.PageSetup.Orientation = wdOrientLandscape
.PageSetup.PageWidth = CentimetersToPoints(42)
.PageSetup.PageHeight = CentimetersToPoints(29.7)
.PageSetup.TopMargin = CentimetersToPoints(1)
.PageSetup.BottomMargin = CentimetersToPoints(1)
.PageSetup.LeftMargin = CentimetersToPoints(1.5)
.PageSetup.RightMargin = CentimetersToPoints(1)
End With
AppWord.Visible = True
‘AppWord.Documents.Add.Range.PasteExcelTable False, False, False
AppWord.ActiveDocument.SaveAs2 PathForFile$ & «» & NameWRD, _
12, False, «», True, «», False, False, False, False, False, 14
AppWord.ActiveDocument.Close
Application.CutCopyMode = False
Set AppWord = Nothing

doober,
просто в моём случае ошибка может быть очевидной, поэтому я подумал, что возможно и не в коде дело и моя ошибка лежит на поверхности

200?’200px’:»+(this.scrollHeight+5)+’px’);»> Dim PathForFile As String
Dim NameWRD As String
Set AppWord = CreateObject(«Word.Application»)
NameWRD = Sheets(1).Range(«НомерЗакупки»).Value & «. Проект решения » & Sheets(1).Range(«ТипПрезентации»).Value & «.docx»
PathForFile$ = ThisWorkbook.Path
Set FSO = CreateObject(«Scripting.FileSystemObject»)
If Not FSO.FolderExists(PathForFile$) Then
FSO.CreateFolder (PathForFile$) ‘
End If
Set FSO = Nothing

AppWord.Documents.Add
AppWord.Selection.Paste
AppWord.Selection.WholeStory
If AppWord.Selection.PageSetup.Orientation = wdOrientPortrait Then
AppWord.Selection.PageSetup.Orientation = wdOrientLandscape
Else
AppWord.Selection.PageSetup.Orientation = wdOrientPortrait
End If
With AppWord.Selection.ParagraphFormat
.SpaceBefore = 0
.SpaceBeforeAuto = False
.SpaceAfter = 0
.SpaceAfterAuto = False
.LineUnitBefore = 0
.LineUnitAfter = 0
.LeftIndent = CentimetersToPoints(0)
.SpaceBeforeAuto = False
.SpaceAfterAuto = False
.SpaceBeforeAuto = False
.SpaceAfterAuto = False
.FirstLineIndent = CentimetersToPoints(0)
End With
With AppWord.Selection
.Font.Name = «Times New Roman»
‘ .Font.Size = 14
.PageSetup.Orientation = wdOrientLandscape
.PageSetup.PageWidth = CentimetersToPoints(42)
.PageSetup.PageHeight = CentimetersToPoints(29.7)
.PageSetup.TopMargin = CentimetersToPoints(1)
.PageSetup.BottomMargin = CentimetersToPoints(1)
.PageSetup.LeftMargin = CentimetersToPoints(1.5)
.PageSetup.RightMargin = CentimetersToPoints(1)
End With
AppWord.Visible = True
‘AppWord.Documents.Add.Range.PasteExcelTable False, False, False
AppWord.ActiveDocument.SaveAs2 PathForFile$ & «» & NameWRD, _
12, False, «», True, «», False, False, False, False, False, 14
AppWord.ActiveDocument.Close
Application.CutCopyMode = False
Set AppWord = Nothing

Сообщение doober,
просто в моём случае ошибка может быть очевидной, поэтому я подумал, что возможно и не в коде дело и моя ошибка лежит на поверхности

Источник

Adblock
detector

0 / 0 / 0

Регистрация: 24.04.2018

Сообщений: 7

1

Excel

18.11.2018, 02:47. Показов 2167. Ответов 3


Доброй ночи
засыпаю и просыпаюсь уже несколько дней с мыслями, как решить проблему
проблема в том, что при вставке из екселя в ворд, таблица вставляется по заданным параметрам через раз
в другой же раз срабатывает ошибка 462, нашел решение для других языков программирования, но для vba не получается решить вопрос. Прошу помочь, заранее благодарен!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

18.11.2018, 02:47

Ответы с готовыми решениями:

Documents.Open метод, ошибка 462.
Помогите разобраться с проблемой. Есть кнопка для открытия вордового файла. Через раз вылетает…

Код работает через раз
Добрый день.
Не могу несколько дней разобраться с одним кодом, работает но почему то через раз (на…

Код выполняется через раз
Учи руби по книги, взял пример, строку.
Запустил — выполнилась, запустил — выполнилась, запустил…

Через раз работает Wi-Fi
Добрый день.
Решил создать новую тему, т.к. перепробовал уже кучу способов по решению проблемы с…

3

asretyq

0 / 0 / 0

Регистрация: 24.04.2018

Сообщений: 7

18.11.2018, 03:19

 [ТС]

2

Visual Basic
1
2
3
4
5
6
7
8
9
wd.Tables(1).Rows.LeftIndent = wa.CentimetersToPoints(-0.2)
 
With wd.Tables(1)
    .PreferredWidth = 0
    .Columns(1).PreferredWidth = wa.CentimetersToPoints(1.5)
    .Columns(2).PreferredWidth = wa.CentimetersToPoints(5.25)
    .Columns(3).PreferredWidth = wa.CentimetersToPoints(9.75)
    .Columns(4).PreferredWidth = wa.CentimetersToPoints(1.5)
End With

чтобы я как я не ковырялся 3 дня, может пригодится… перед

Visual Basic
1
CentimetersToPoints(1.5)

прописывается переменная на

Visual Basic
1
wa=Word.Application

точного ответа видимо вы не хотите давать… как-то усложняете речами…



0



6874 / 2806 / 533

Регистрация: 19.10.2012

Сообщений: 8,552

18.11.2018, 14:40

3

Вот смотрите — есть
Function CentimetersToPoints(Centimeters As Double) As Double
Member of Excel.Application
и есть
Function CentimetersToPoints(Centimeters As Single) As Single
Member of Word.Application

Нужно же как-то объяснить глупой машине что подразумевали…
Да и не только ей — я вот например тоже не в курсе
А примеры ни о чём — где там искать кривое

Цитата
Сообщение от asretyq
Посмотреть сообщение

при вставке из екселя в ворд

Добавлено через 1 минуту

Цитата
Сообщение от asretyq
Посмотреть сообщение

как-то усложняете речами..

а ведь никто и слова не сказал



0



0 / 0 / 0

Регистрация: 24.04.2018

Сообщений: 7

18.11.2018, 18:02

 [ТС]

4

Hugo121, о привет)) видел вас и на другом екселевском сайте))
просто я читал решения этой проблемы, люди объясняют вокруг да около и не могу конктретно указать что добавить к коду для избежания ошибки.
я только вчера узнал, что для размерности напр. CentimetersToPoints также указывается переменная. Предпочитаю без function обойтись, у меня например норм робит



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

18.11.2018, 18:02

4

  • Remove From My Forums
  • Question

  • I am trying to access a webpage from excel using VBA. I can get internet explorer to launch, and I see the webpage come up, but I get a runtime error 462 when I hit the Do Until internet.ReadyState >= 4 line of code. any ideas? ultimately I want to be able
    to parse a site and get a list of the links on that site and pick one, and then «click» on that link. suggestions and help would be great. here is the function (that I found on the web) that I am using:

    Public Sub clicklick()

    Dim internet As Object
    Dim internetdata As Object
    Dim div_result As Object
    Dim header_links As Object
    Dim link As Object
    Dim URL As String
    
    Set internet = CreateObject("InternetExplorer.Application")
    internet.Visible = True
    
    URL = "https://www.google.co.in/search?q=how+to+program+in+vba"
    internet.Navigate URL
    
    
    Do Until internet.ReadyState >= 4
        DoEvents
    Loop
    
    Application.Wait Now + TimeSerial(0, 0, 5)
    
    Set internetdata = internet.Document
    Set div_result = internetdata.getelementbyid("res")
    
    
    Set header_links = div_result.getelementsbytagname("h3")
    
    For Each h In header_links
        Set link = h.ChildNodes.Item(0)
        Cells(Range("A" & Rows.count).End(xlUp).row + 1, 1) = link.href
    Next
    
    MsgBox "done"

    End Sub

    thank you, alan

Модератор:Naeel Maqsudov

Putincev

Сообщения:38
Зарегистрирован:10 май 2007, 16:06

Добрый день!
Перешел с MS Office 2003 на MS Office 2007, и получил огромную проблему.
При формировании программно файла Excel, с созданием в нем новых листов, при запуске во 2-ой раз, возникает ошибка — Run-time error ‘462’: «The remote server machine does not exist or is unavailable».
В 2003 такой ошибки не было, я перед запуском программы проверял на наличие в ОП Excel и удалял его (см. в приложении). А как отключить какой-то сервер я не знаю.
Для 2003 мне программист написал утилитку для удаления Excel из ОП и я этим пользовался, в 2007 эта утилитка работает, но Excel остается где-то в не доступном и не обозримом месте. Поэтому просто после формирования файла я закрываю (quit) Access, а потом снова запускаю его. Возможно есть способ отключать программно Excel в 2007 и работать дальше без выхода из Access?

У вас нет необходимых прав для просмотра вложений в этом сообщении.

pashulka

Сообщения:831
Зарегистрирован:24 ноя 2004, 03:46
Контактная информация:

28 июл 2015, 21:30

Замените

Код: Выделить всё

objXL.Sheets(Array("Nakl", "Rees")).Copy After:=Sheets(intListovN)

на

Код: Выделить всё

objXL.Sheets(Array("Nakl", "Rees")).Copy After:=objXL.Sheets(intListovN)

И, на всякий случай, перед Set objXL = Nothing явно закройте книгу и приложение.

Putincev

Сообщения:38
Зарегистрирован:10 май 2007, 16:06

29 июл 2015, 16:57

это у меня из-за того, что я явно не указал, к какой книге обращаться?
еще не пробовал, но большое спасибо, завтра попробую и отпишусь

pashulka

Сообщения:831
Зарегистрирован:24 ноя 2004, 03:46
Контактная информация:

  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • RESOLVED: [VBA Word/Excel] Error 462 when running the code twice

  1. Dec 12th, 2011, 10:15 PM


    #1

    Earlien is offline

    Thread Starter


    Member


    Smile RESOLVED: [VBA Word/Excel] Error 462 when running the code twice

    Hi, this is my first post, so if I’ve done something wrong like forgotten code tags or posted in the wrong section, please don’t yell at me

    Before I explain the problem, I want to say that I am aware other people have posted this same problem, even on this website, but the solutions that seem to be working for everyone else have not worked for me. I have researched this problem for some 5 hours now and spent days trying to resolve it. Some examples of other threads that I have read with the same issue:

    HTML Code:

    http://www.vbforums.com/showthread.php?t=569061
    http://www.tushar-mehta.com/excel/vba/xl_doesnt_quit/
    http://support.microsoft.com/kb/189618

    The issue is that I am writing code in VBA Word which calls an instance of Excel, does some stuff, and then closes Excel. Running the code again a second time usually results in the infamous error 462: «The remote server machine does not exist or is unavailable».

    The Microsoft knowledge base (link above) advises to «Modify the code so that each call to a Word object, method, or property is qualified with the appropriate object variable.» I have gone through with a fine tooth comb and made sure that everything is qualified and referenced correctly and explicitly.

    Furthermore, after reading the second article (link above) I have used late-binding on their suggestion to remove the issue of the Excel application continuing to run in the background after its supposed to be closed. I have found the [first instance of] offending line which causes the Excel app to continue to run, which, if omitted, makes the problem go away.

    The code is quite lengthy so I will only post the relevant parts:

    Code:

    Private Filepath As String
    Private First_Row As Long, Last_Row As Long, First_Col As Integer, Last_Col As Integer
    Private XL_App As Object         'Late-binding
    Private XL_Wb As Object
    
    Option Explicit
    
    'Main sub procedure
    Public Main()
    
        Dim Filename As String
    
    Top:
        On Error GoTo Error_Handler
    
        Filepath = Application.ActiveDocument.Path & "CommonData.xls"
        
        'Determine if an instance of Excel is already running
        Set XL_App = GetObject(, "Excel.Application")
        'If no instance of Excel can be found, Error handler will tell VBA to resume next
    
        'Determine if the data file workbook is already open (if Excel was found above)
        If Not XL_App Is Nothing Then
            Filename = Get_File_Name(Filepath)
            For i = 1 To XL_App.Workbooks.Count
                If XL_App.Workbooks(i).Name = Filename Then
                    Set XL_Wb = XL_App.Workbooks(i)
                    Exit For
                End If
            Next i
        End If
        
        'If no instance of Excel with the workbook can be found, create one
        If XL_Wb Is Nothing Then
            Set XL_App = CreateObject("Excel.Application")
            XL_App.Visible = False
            Set XL_Wb = XL_App.Workbooks.Open(Filepath)
        End If
        
        'Determine actual used range of worksheet
        If XL_App.WorksheetFunction.CountA(XL_Wb.Sheets(1).Cells) > 0 Then
            First_Row = XL_App.Cells.Find(what:="*", SearchDirection:=xlNext, SearchOrder:=xlByRows).Row
            First_Col = XL_App.Cells.Find(what:="*", SearchDirection:=xlNext, SearchOrder:=xlByColumns).Column
            Last_Row = XL_App.Cells.Find(what:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByRows).Row
            Last_Col = XL_App.Cells.Find(what:="*", SearchDirection:=xlPrevious, SearchOrder:=xlByColumns).Column
        End If
            
        'Get data
        'Insert dummy column and copy unique records to it
        XL_Wb.Worksheets(1).Columns(1).EntireColumn.Insert
        XL_Wb.Worksheets(1).Range(Cells(First_Row, First_Col), Cells(Last_Row, First_Col)).Select
        
        XL_App.Selection.AdvancedFilter Action:=xlFilterCopy, CopyToRange:=XL_Wb.Worksheets(1).Range("A1"), Unique:=True
        
        'Do other stuff
        
        'Remove dummy column
        XL_Wb.Worksheets(1).Columns(1).EntireColumn.Delete
        
        'Close Excel
        XL_Wb.Close False
        XL_App.Quit
        Set XL_Wb = Nothing
        Set XL_App = Nothing
    
        Exit Sub
        
    Error_Handler:
        Select Case Err.Number
            Case 429, 91
                Err = 0
                Resume Next
            Case Else
                MsgBox ("An unexpected error has occured." & vbCrLf & vbCrLf & _
                "Error number: " & Err.Number & vbCrLf & "Error description: " & Err.Description)
                Resume Next
        End Select
    
    End Sub

    The code in red is where the error message appears when it is run a second time. However, it seems that Excel is reference properly here, so no idea why this is occurring. I have tried the following variations with no success:

    Code:

    XL_Wb.Range(Cells(First_Row, First_Col), Cells(Last_Row, First_Col)).Select
    XL_Wb.Worksheets(1).Range(Cells(First_Row, First_Col), Cells(Last_Row, First_Col)).Select
    XL_App.Application.Workbooks(1).Worksheets(1).Range(Cells(First_Row, First_Col), Cells(Last_Row, First_Col)).Select
    XL_App.Application.Workbooks(1).Sheets(1).Range(Cells(First_Row, First_Col), Cells(Last_Row, First_Col)).Select

    Note that the above code is not resolving the original error of having the Excel app continuing to run in the background. I am in the middle of trying to fix this when I started getting the Error 462. To isolate the latter, add an early exit like:

    Code:

    '...
        XL_Wb.Worksheets(1).Range(Cells(First_Row, First_Col), Cells(Last_Row, First_Col)).Select
    
        GoTo Temp_End_Early
    
    '...
    
    Temp_End_Early:
        'Close Excel
        XL_Wb.Close False
        XL_App.Quit
        Set XL_Wb = Nothing
        Set XL_App = Nothing
    
        Exit Sub
    
    '...

    Hope this makes sense, and hope someone can help, because I am at the end of my tether…

    Last edited by Earlien; Jan 3rd, 2012 at 07:22 PM.

    Reason: Problem resolved


  2. Dec 13th, 2011, 04:07 AM


    #2

    Re: [VBA Word/Excel] Error 462 when running the code twice

    XL_Wb.Worksheets(1).Range(Cells(First_Row, First_Col), Cells(Last_Row, First_Col)).Select

    as you do not specify which sheet the cells are on, you are leaving yourself open to error, by default it would refer to cells on the activesheet, if for any reason someother sheet is considered to be the active sheet, error would occur
    this may not be the cause for your error, but i would fix that first

    try to avoid selecting any range, filter the range rather than the selection

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  3. Dec 19th, 2011, 05:47 PM


    #3

    Earlien is offline

    Thread Starter


    Member


    Re: [VBA Word/Excel] Error 462 when running the code twice

    Hi westconn1,

    Thanks for your reply. Unfortunately I do not understand what you mean — I thought I had specified which sheet the cells are on:

    Code:

    XL_Wb.Worksheets(1).Range(Cells(First_Row, First_Col), Cells(Last_Row, First_Col)).Select

    Can you please clarify what you mean and provide example code?


  4. Dec 19th, 2011, 05:59 PM


    #4

    Re: [VBA Word/Excel] Error 462 when running the code twice

    Not quite… you have only specified which sheet the Range is on, you have not specified a sheet for the Cells later in that line:

    Code:

    XL_Wb.Worksheets(1).Range(XL_Wb.Worksheets(1).Cells(First_Row, First_Col), XL_Wb.Worksheets(1).Cells(Last_Row, First_Col)).Select


  5. Dec 19th, 2011, 06:05 PM


    #5

    Earlien is offline

    Thread Starter


    Member


    Re: [VBA Word/Excel] Error 462 when running the code twice

    Thank you si_the_geek,

    I had no idea you had to specify this inside the range as well!

    It seems kind of superfluous that you would need to specify what sheet the cells are on if the sheet for the range is already specified. I mean, this implies you could have a range on one sheet, whose arguments are the cells from another worksheet? I don’t follow this logic.

    Nonetheless, I will try your suggestion and get back to you to see if this solves the problem.


  6. Dec 19th, 2011, 06:15 PM


    #6

    incidentals is offline


    Frenzied Member


    Re: [VBA Word/Excel] Error 462 when running the code twice

    this stuff does my head in…

    what is the value of first_row
    If XL_App.WorksheetFunction.CountA(XL_Wb.Sheets(1).Cells) > 0
    is not true?

    is it undefined or 0 and if it and its pals are 0 what does that do for Cells(0,0)

    Am I close?


  7. Dec 19th, 2011, 06:35 PM


    #7

    Re: [VBA Word/Excel] Error 462 when running the code twice

    If the value of first_row is not changed, it will be whatever value it was before.

    The data type is Long, so the initial value (before you set it to anything) will be 0.

    However, as you have declared it outside of the Sub, running the Sub again means that it could accidentally re-use whatever value the Sub assigned to it the last time — and that could cause problems. To avoid that, always give it and the related variables a value (either before the If, or in an Else).

    Note also that your code to set those variables is not reliable:

    First_Row = XL_App.Cells.Find(what:=»*», SearchDirection:=xlNext, SearchOrder:=xlByRows).Row

    ..because you are not specifying which Sheet (or even Workbook) the Cells belong to.

    Quote Originally Posted by Earlien
    View Post

    It seems kind of superfluous that you would need to specify what sheet the cells are on if the sheet for the range is already specified. I mean, this implies you could have a range on one sheet, whose arguments are the cells from another worksheet? I don’t follow this logic.

    I agree with it being superfluous, but it is technically required — because as far as VB is concerned they are entirely separate things (the Cells are evaluated separately, and then passed to the Range).

    The implication is correct, but it wont work properly (you should get an error, but may just get a bug instead).


  8. Dec 20th, 2011, 04:21 AM


    #8

    Re: [VBA Word/Excel] Error 462 when running the code twice

    is it undefined or 0 and if it and its pals are 0 what does that do for Cells(0,0)

    cells(0, 0) is an error anyway as row 0 or column 0 does not exist

    the simple way to specify which sheet, the cells and range and any other,

    vb Code:

    1. with sheets("sheet1")

    2.       .range(.cells(rw, col), .cells(rw1, col1)).select

    3. end with

    or use a sheet object

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  9. Dec 20th, 2011, 03:19 PM


    #9

    incidentals is offline


    Frenzied Member


    Re: [VBA Word/Excel] Error 462 when running the code twice

    and I think that wopuld be enough to give you the error


  10. Jan 3rd, 2012, 07:16 PM


    #10

    Earlien is offline

    Thread Starter


    Member


    Re: [VBA Word/Excel] Error 462 when running the code twice

    Sorry for the delayed response — I had other projects to complete before Christmas and have only returned to the office yesterday.

    To anyone reading this thread — implementing si_the_geek’s suggestion solves the problem. I’m still finding this hard to accept that you need to specify the worksheet three times (unless using a with block statement), but I’m happy this is finally resolved (for now). Thank you


  11. Jan 3rd, 2012, 07:21 PM


    #11

    Earlien is offline

    Thread Starter


    Member


    Re: [VBA Word/Excel] Error 462 when running the code twice

    Umm…how do I edit the thread title to mark it as resolved?

    Edit: Nvm, worked it out . You have to use the «Go Advanced» options after editing the post.

    Last edited by Earlien; Jan 3rd, 2012 at 07:24 PM.


  12. Jan 5th, 2012, 05:04 AM


    #12

    Re: RESOLVED: [VBA Word/Excel] Error 462 when running the code twice

    You have to use the «Go Advanced» options

    or use thread tools

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  13. Jul 16th, 2016, 03:25 AM


    #13

    stein1991 is offline


    New Member


    Re: RESOLVED: [VBA Word/Excel] Error 462 when running the code twice

    Hello guys,

    I ‘ve read your answers and tried to figure what’s wrong with my code and error 462 occurs in ms access

    what i can not understand is why the error occurs every Second time the code is executed

    here is my code :
    Dim WordApp As Word.Application
    Dim WordDoc As Word.Document

    On Error Resume Next
    Set WordApp = GetObject(, «Word.Application»)

    If Err.Number > 0 Then Set WordApp = CreateObject(«Word.Application»)
    On Error GoTo 0

    With WordApp
    .Visible = True

    .DisplayAlerts = 0

    On Error Resume Next
    Set WordDoc = Documents(«TestDoc»)
    If Err.Number > 0 Then
    Set WordDoc = .Documents.Add
    WordDoc.SaveAs CurrentProject.Path & «TestDoc.doc»
    End If
    On Error GoTo 0

    ‘Set WordDoc = .Documents.Add
    ‘WordDoc.SaveAs CurrentProject.Path & «TestDoc.doc»

    End With ‘WordApp

    With WordApp.Selection

    .Font.Name = «Arial»
    .Font.Size = 12

    .TypeText «Some Random Text»
    .TypeParagraph

    With WordDoc.PageSetup
    .LeftMargin = CentimetersToPoints(3.5)
    .RightMargin = CentimetersToPoints(2.5)
    .TopMargin = CentimetersToPoints(2.5)
    .BottomMargin = CentimetersToPoints(1.5)
    End With

    ‘Add header and footer
    WordDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text = WordDoc.Path & _
    «» & WordDoc.Name
    End With

    Dim aPar As Paragraph
    For Each aPar In WordDoc.Paragraphs
    aPar.Alignment = 3
    Next aPar

    WordDoc.Save

    Set WordDoc = Nothing
    Set WordApp = Nothing
    Set aPar = Nothing


  14. Jul 16th, 2016, 06:27 AM


    #14

    Re: RESOLVED: [VBA Word/Excel] Error 462 when running the code twice

    on which line does the error occur?

    this line should be

    Code:

    Set WordDoc = .Documents("TestDoc")

    and assumes that the specific document is already open

    i do not see any other reason why the code should fail on the second run

    this has to assume some specific range is already selected, better to use a fully qualified range

    i do my best to test code works before i post it, but sometimes am unable to do so for some reason, and usually say so if this is the case.
    Note code snippets posted are just that and do not include error handling that is required in real world applications, but avoid On Error Resume Next

    dim all variables as required as often i have done so elsewhere in my code but only posted the relevant part

    come back and mark your original post as resolved if your problem is fixed
    pete


  • Home
  • VBForums
  • Visual Basic
  • Office Development
  • RESOLVED: [VBA Word/Excel] Error 462 when running the code twice


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Понравилась статья? Поделить с друзьями:
  • Error 451 utorrent
  • Error 451 unavailable for legal reasons
  • Error 451 geofence blocked
  • Error 4503 tp link
  • Error 4502 generic что это