Макрос по созданию файла MS WORD. run-time error 462 |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
Содержание
- 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
- Symptoms
- Cause
- Resolution
- Status
- More Information
- Steps to Reproduce Behavior
- References
- 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
- Symptoms
- Cause
- Resolution
- Status
- More Information
- Steps to Reproduce Behavior
- References
- Excel automation fails second time code runs
- Symptoms
- Cause
- Resolution
- Status
- More Information
- Steps to reproduce the behavior
- References
- Vba runtime error 462 word
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
Symptoms
When you run Microsoft Visual Basic code that uses Automation to control Microsoft Word, you may receive one of the following error messages:
Error message 1
Run-time error ‘-2147023174’ (800706ba)
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 Word due to a line of code that calls a Word object, method, or property without qualifying it with a Word 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 once.
Resolution
Modify the code so that each call to a Word object, method, or property is qualified with the appropriate object variable.
Status
This behavior is by design.
More Information
To automate Word, you establish an object variable that usually refers to the Word Application or Document object. Other object variables can then be set to refer to a Selection, a Range, or other objects in the Word object model. When you write code to use a Word object, method, or property, you should always precede the call with the appropriate object variable. If you do not, Visual Basic uses a hidden global variable reference which it sets to the currently running instance. If Word is shutdown, or if the declared object variable is released, the hidden global variable will now reference an invalid (destroyed) object. When running the automation code again, calls to this hidden object variable will fail with the aforementioned error.
The following steps illustrate how to reproduce this problem, and how to correct it.
Steps to Reproduce Behavior
Start a new Standard EXE project in Visual Basic. Form1 is created by default.
Click References from the Project menu, and then click one of the following options:
For Office Word 2007, click Microsoft Word 12.0 Object Library
For Word 2003, click Microsoft Word 11.0 Object Library
For Word 2003, click Microsoft Word 10.0 Object Library
For Word 2000, click Microsoft Word 9.0 Object Library.
For Word 97, click Microsoft Word 8.0 Object Library.
Place a CommandButton on Form1.
Copy the following code to the Code Window of Form1:
On the Run menu, click Start or press the F5 key to start the program.
Click the CommandButton. No error occurs. However, a reference to Word has been created and has not been released.
Click the CommandButton again and note that you receive the error previously described.
Note The error occurs because the code refers to the InchesToPoints Method without preceding the call with the oWord object variable.
Stop the project and change the following line:
Run the program again. Then, click the CommandButton. No error occurs.
Click the CommandButton again and note that you receive the error.
Note The error occurs because the code refers to the ActiveDocument Section one’s Range object without preceding the call with the oWord object variable.
Stop the project and change the following line:
Run the program again. Note that you can run the code multiple times without error.
When building a Visual Basic project automating Word, if your project has a reference to the Microsoft Word Object Library, sample code for the objects, methods, and properties of the Word Object Model is available from the Word Help file. When the cursor is over a key word in your code, you will see any applicable Help text by pressing the F1 key.
The sample code in the Help topic will be the Microsoft Word Visual Basic for Applications code. It will not show the object references that your Visual Basic code requires. You will need to add the qualifiers as appropriate.
References
For additional information, please see the following articles in the Microsoft Knowledge Base:
178510 PRB: Excel Automation Method of Object ‘_Global’Failed
167223 Microsoft Office 97 Automation Help File Available
For additional information about the Automation of Office applications, click the article number below to view the article in the Microsoft Knowledge Base:
222101 HOWTO: Find and Use Office Object Model Documentation
Источник
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
Symptoms
When you run Microsoft Visual Basic code that uses Automation to control Microsoft Word, you may receive one of the following error messages:
Error message 1
Run-time error ‘-2147023174’ (800706ba)
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 Word due to a line of code that calls a Word object, method, or property without qualifying it with a Word 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 once.
Resolution
Modify the code so that each call to a Word object, method, or property is qualified with the appropriate object variable.
Status
This behavior is by design.
More Information
To automate Word, you establish an object variable that usually refers to the Word Application or Document object. Other object variables can then be set to refer to a Selection, a Range, or other objects in the Word object model. When you write code to use a Word object, method, or property, you should always precede the call with the appropriate object variable. If you do not, Visual Basic uses a hidden global variable reference which it sets to the currently running instance. If Word is shutdown, or if the declared object variable is released, the hidden global variable will now reference an invalid (destroyed) object. When running the automation code again, calls to this hidden object variable will fail with the aforementioned error.
The following steps illustrate how to reproduce this problem, and how to correct it.
Steps to Reproduce Behavior
Start a new Standard EXE project in Visual Basic. Form1 is created by default.
Click References from the Project menu, and then click one of the following options:
For Office Word 2007, click Microsoft Word 12.0 Object Library
For Word 2003, click Microsoft Word 11.0 Object Library
For Word 2003, click Microsoft Word 10.0 Object Library
For Word 2000, click Microsoft Word 9.0 Object Library.
For Word 97, click Microsoft Word 8.0 Object Library.
Place a CommandButton on Form1.
Copy the following code to the Code Window of Form1:
On the Run menu, click Start or press the F5 key to start the program.
Click the CommandButton. No error occurs. However, a reference to Word has been created and has not been released.
Click the CommandButton again and note that you receive the error previously described.
Note The error occurs because the code refers to the InchesToPoints Method without preceding the call with the oWord object variable.
Stop the project and change the following line:
Run the program again. Then, click the CommandButton. No error occurs.
Click the CommandButton again and note that you receive the error.
Note The error occurs because the code refers to the ActiveDocument Section one’s Range object without preceding the call with the oWord object variable.
Stop the project and change the following line:
Run the program again. Note that you can run the code multiple times without error.
When building a Visual Basic project automating Word, if your project has a reference to the Microsoft Word Object Library, sample code for the objects, methods, and properties of the Word Object Model is available from the Word Help file. When the cursor is over a key word in your code, you will see any applicable Help text by pressing the F1 key.
The sample code in the Help topic will be the Microsoft Word Visual Basic for Applications code. It will not show the object references that your Visual Basic code requires. You will need to add the qualifiers as appropriate.
References
For additional information, please see the following articles in the Microsoft Knowledge Base:
178510 PRB: Excel Automation Method of Object ‘_Global’Failed
167223 Microsoft Office 97 Automation Help File Available
For additional information about the Automation of Office applications, click the article number below to view the article in the Microsoft Knowledge Base:
222101 HOWTO: Find and Use Office Object Model Documentation
Источник
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
Источник
Vba runtime error 462 word
Здесь обсуждаются вопросы по языку Visual Basic 1-6 (а так же по схожим языкам, как, например, PowerBASIC).
Вопросы по Visual Basic .NET (это который входит в состав Visual Studio 2002/2003/2005/2008+, для тех, кто не в курсе) обсуждаются в разделе .NET.
Обратите внимание:
1. Прежде чем начать новую тему или отправить сообщение, убедитесь, что Вы не нарушаете правил форума!
2. Обязательно воспользуйтесь поиском. Возможно, Ваш вопрос уже обсуждали. Полезные ссылки приведены ниже.
3. Темы с просьбой выполнить какую-либо работу за автора в этом разделе не обсуждаются. Студенты, вам сюда: ПОМОЩЬ СТУДЕНТАМ !
4. Используйте теги [ code=vba ] . текст программы. [ /code ] для выделения текста программы подсветкой.
5. Помните, здесь телепатов нет. Формулируйте свой вопрос максимально грамотно и чётко: Как правильно задавать вопросы
6. Запрещено отвечать в темы месячной (и более) давности, без веских на то причин.
Полезные ссылки:
FAQ Сайта
FAQ Раздела
Кладовка
Наши Исходники
API-Guide
Поиск по Разделу
MSDN Library Online
Google
Ваше мнение о модераторах: SCINER, B.V.
Источник
- 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
Все доброй ночи!
Очень извиняюсь, что касаюсь избитой темы (наверное), но что-то я не смог найти ответа в таком форуме, хотя регулярно пользуюсь подсказками пользователей. До сей поры хватало.
Суть вот в чем:
Я хочу из существующей таблицы 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 офисе такой проблемы не возникнет? А то будет жаль перставлять из-за этого…..
Все харанее спасибо.
0 / 0 / 0 Регистрация: 24.04.2018 Сообщений: 7 |
|
1 |
|
Excel 18.11.2018, 02:47. Показов 2216. Ответов 3
Доброй ночи
__________________
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 |
|||||||||||
чтобы я как я не ковырялся 3 дня, может пригодится… перед
прописывается переменная на
точного ответа видимо вы не хотите давать… как-то усложняете речами…
0 |
6874 / 2806 / 533 Регистрация: 19.10.2012 Сообщений: 8,552 |
|
18.11.2018, 14:40 |
3 |
Вот смотрите — есть Нужно же как-то объяснить глупой машине что подразумевали…
при вставке из екселя в ворд Добавлено через 1 минуту
как-то усложняете речами.. а ведь никто и слова не сказал
0 |
0 / 0 / 0 Регистрация: 24.04.2018 Сообщений: 7 |
|
18.11.2018, 18:02 [ТС] |
4 |
Hugo121, о привет)) видел вас и на другом екселевском сайте))
0 |
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
18.11.2018, 18:02 |
4 |