Vba runtime error 462 word

Группа: Пользователи

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

rvshestakov

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

Группа: Пользователи

Ранг: Участник

Сообщений: 56


Репутация:

6

±

Замечаний:
0% ±


Excel 2010

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

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

 

Ответить

doober

Дата: Четверг, 19.03.2015, 17:22 |
Сообщение № 2

Группа: Друзья

Ранг: Ветеран

Сообщений: 906


Репутация:

317

±

Замечаний:
0% ±


Excel 2010

Код макроса прикладывать пока не буду

Здесь вам помогут без кода макроса.


 

Ответить

rvshestakov

Дата: Пятница, 20.03.2015, 06:36 |
Сообщение № 3

Группа: Пользователи

Ранг: Участник

Сообщений: 56


Репутация:

6

±

Замечаний:
0% ±


Excel 2010

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

[vba]

Код

     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

[/vba]

Сообщение отредактировал rvshestakovПятница, 20.03.2015, 06:41

 

Ответить

rvshestakov

Дата: Пятница, 20.03.2015, 06:42 |
Сообщение № 4

Группа: Пользователи

Ранг: Участник

Сообщений: 56


Репутация:

6

±

Замечаний:
0% ±


Excel 2010

Ужас, что происходит с форматированием блока (/code)? <_<
на предпросмотре, всё корректно отображается.
[moder]Потому что для кода надо использовать [vba][code] (кнопка #)[/moder]

 

Ответить

Manyasha

Дата: Пятница, 20.03.2015, 07:39 |
Сообщение № 5

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

rvshestakov, нужно сначало проверить, запущено ли приложение word:[vba]

Код

   On Error Resume Next
     Set AppWord = GetObject(, «Word.Application»)
     If Err <> 0 Then
           Set AppWord = CreateObject(«Word.Application»)
     End If
     On Error GoTo 0

[/vba]
А потом уже можно работать с файлами[vba]

Код

   AppWord.Documents.Add

[/vba]


ЯД: 410013299366744 WM: R193491431804

Сообщение отредактировал ManyashaПятница, 20.03.2015, 07:40

 

Ответить

rvshestakov

Дата: Пятница, 20.03.2015, 09:51 |
Сообщение № 6

Группа: Пользователи

Ранг: Участник

Сообщений: 56


Репутация:

6

±

Замечаний:
0% ±


Excel 2010

Manyasha, добавил. не помогло :(

 

Ответить

rvshestakov

Дата: Пятница, 20.03.2015, 10:01 |
Сообщение № 7

Группа: Пользователи

Ранг: Участник

Сообщений: 56


Репутация:

6

±

Замечаний:
0% ±


Excel 2010

комментарии с саппорта Майкрософта:
Visual Basic устанавливает ссылку на Excel из-за наличия в коде строки, вызывающей объект, метод или свойство Excel без квалификации элемента с помощью объектной переменной Excel. Visual Basic не освобождает эту ссылку до завершения работы программы. Эта ошибочная ссылка конфликтует с кодом автоматизации, если этот код выполняется более одного раза.
Чтобы устранить эту проблему, измените код таким образом, чтобы каждый вызов объекта, метода или свойства Excel квалифицировался соответствующей объектной переменной.

тоже не помогло.

 

Ответить

Manyasha

Дата: Пятница, 20.03.2015, 10:59 |
Сообщение № 8

Группа: Модераторы

Ранг: Старожил

Сообщений: 2198


Репутация:

898

±

Замечаний:
0% ±


Excel 2010, 2016

rvshestakov, Вы же сами решение и описали:

измените код таким образом, чтобы каждый вызов объекта, метода или свойства Excel квалифицировался соответствующей объектной переменной.

Везде, где вызываются методы, привяжите их к объекту ворда, например
[vba]

Код

    With AppWord.Selection.ParagraphFormat
           .SpaceBefore = 0
           .SpaceBeforeAuto = False
           .SpaceAfter = 0
           .SpaceAfterAuto = False
           .LineUnitBefore = 0
           .LineUnitAfter = 0
           .LeftIndent = AppWord.CentimetersToPoints(0)’изменила
           .SpaceBeforeAuto = False
           .SpaceAfterAuto = False
           .SpaceBeforeAuto = False
           .SpaceAfterAuto = False
           .FirstLineIndent = AppWord.CentimetersToPoints(0)’изменила
       End With

[/vba]
Аналогично и в других строчках. Не [vba]

Код

.PageSetup.PageWidth = CentimetersToPoints(42)

[/vba]а вот так[vba]

Код

.PageSetup.PageWidth = AppWord.CentimetersToPoints(42)

[/vba]

Если не получится, прикладывайте пример.


ЯД: 410013299366744 WM: R193491431804

Сообщение отредактировал ManyashaПятница, 20.03.2015, 11:01

 

Ответить

rvshestakov

Дата: Пятница, 20.03.2015, 12:21 |
Сообщение № 9

Группа: Пользователи

Ранг: Участник

Сообщений: 56


Репутация:

6

±

Замечаний:
0% ±


Excel 2010

Manyasha, спасибо за помощь. всё в порядке теперь (пока что) :)
Мой случай заболевания — «смотрю в книгу, вижу фигу».

 

Ответить

Содержание

  1. 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
  2. Symptoms
  3. Cause
  4. Resolution
  5. Status
  6. More Information
  7. Steps to Reproduce Behavior
  8. References
  9. 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
  10. Symptoms
  11. Cause
  12. Resolution
  13. Status
  14. More Information
  15. Steps to Reproduce Behavior
  16. References
  17. Excel automation fails second time code runs
  18. Symptoms
  19. Cause
  20. Resolution
  21. Status
  22. More Information
  23. Steps to reproduce the behavior
  24. References
  25. 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


Доброй ночи
засыпаю и просыпаюсь уже несколько дней с мыслями, как решить проблему
проблема в том, что при вставке из екселя в ворд, таблица вставляется по заданным параметрам через раз
в другой же раз срабатывает ошибка 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

Понравилась статья? Поделить с друзьями:
  • Vba runtime error 2147467259
  • Vba runtime error 13 type mismatch как исправить
  • Vba run time error 76 path not found
  • Vba run time error 5941
  • Vba run time error 40036