Ошибка 5981 эксель

Внимание, откроется в новом окне.
PDFПечать

Проблема характерна для старших версий MS Office (2010 и выше).

При создании документов (протоколов или сводных отчетов) возможно возникновение ошибки «5981 — Не удается открыть банк макросов», как показано на рисунке.

Дополнительно данная ошибка может сопровождаться еще одной ошибкой (Error «5460 — Ошибка файла»), которая также возникает при создании новых документов.

Причиной данных ошибок является блокировка шаблонов программы из-за особого режима безопасности MS Word (блокируются файлы, полученные  из Internet, из внешнего источника или из сетевой папки).

Проблема характеризуется последующими сообщениями над документом, который подвергся блокировке, как показано на рисунке.

Можно применить изменения к конкретному шаблону, используя кнопки «Разрешить редактирование» или «Включить содержимое», но лучше это сделать для всех используемых шаблонов, как описано ниже.

Известны 2 случая, которые приводят к блокировкам со стороны MS Word.

1 Случай. Блокируются шаблоны из стандартной папки templates другого ПК и воспринимаются MS Word как файлы из внешнего источника.

В данной ситуации необходимо добавить папку с шаблонами в надежные расположения MS Word через меню «Файл — Параметры», как показано на рисунке.

Путь к папке с шаблонами по умолчанию: C:\ProgramData\attest5\5.1\templates

Папка с шаблонами по умолчанию находится в папке с настройками пользователя. Где хранятся настройки пользователя дополнительно можно ознакомиться в следующем МАТЕРИАЛЕ.

2 Случай. Для шаблонов настроена отдельная папка templates.

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

2 / 2 / 0

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

Сообщений: 90

1

27.03.2019, 14:57. Показов 3875. Ответов 3


Студворк — интернет-сервис помощи студентам

Здравствуйте, уважаемые форумчане!
Есть код, который заполняет шаблон Word (расширение .dotx), данными из таблицы Excel.
Но есть проблема: на одном компьютере код работает отлично, а на другом в момент создания документа выбивается ошибка: application-defind or object-defind error Номер ошибки 5981. Происходит она вот в этой строке:
Set WD = WA.Documents.Add(путь к папке с шаблоном и его имя).
Что может быть не так?



0



ᴁ®

Эксперт MS Access

3456 / 1842 / 387

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

Сообщений: 6,295

Записей в блоге: 4

27.03.2019, 15:00

2

vasilisaegorovn, скорее всего не правильно зарегистрирована библиотека. Разрядность компов разная.
Проверьте библиотеки на сбойном. (Referens)



1



2 / 2 / 0

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

Сообщений: 90

27.03.2019, 18:13

 [ТС]

3

АЕ, в решении проблемы на втором компьютере помогло следующее:
Сделала приложение ворд visible=true. И когда выбило ошибку — зашла в открытый на основе шаблона документ и нажала там «Разрешить редактировать». Затем вернула visible=false. И теперь все работает.
НО!!! как избежать этого при передаче файла другим пользователям, у которых потенциально тоже может возникнуть эта ошибка?

Добавлено через 1 час 33 минуты
Вдруг кто столкнётся с такой же проблемой и вот решение: нужно в свойствах переданного по интернету шаблона разрешить его редактирование)
Всем спасибо!



1



ᴁ®

Эксперт MS Access

3456 / 1842 / 387

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

Сообщений: 6,295

Записей в блоге: 4

27.03.2019, 21:29

4

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

свойствах переданного по интернету шаблона разрешить его редактирование

Как правило это определенная папка. Вот ее и надо в параметрах безопасности ворда указать как довереное расположение



0



I’ve created macro in excel 2013 where I point some data from excel to Word (via word template).
in excel 2013 everything works perfectly, but now I have to run this excel also in older company PC where is installed only M$ Office 2010/win7 — fresh installation.

Set objDoc = objWord.Documents.Add(Template:=ThisWorkbook.Sheets("Data").Range("O1").Value & ThisWorkbook.Sheets("Data").Range("G2").Value)

in this excel 2010 I get run-time error 5981 (application-defined or object-defined error).

in cell «O1» is file folder where are this excel + word templates saved
cell «G2» contain info which template should be used (according to dropdown selection).

update: I’ve checked this on other PC with office 2010 and it works. Probably some add-in/library is not working correctly, but idk how to check it.

asked Jul 21, 2015 at 10:31

tryzhas's user avatar

1

Error 5981 seems to have two descriptions attached to it (why?):

  1. Could not open macro storage
  2. Application-defined or object-defined error

Since I got the second description I can only comment on that one, although «Could not open macro storage» seems to suggest that there is something wrong with (the macro’s in) the Word file itself.

In my situation the cause of error 5981 was that the Word-template was not a trusted document.
When opening the Word-template manually, it was opened in protected view. When opening the template automatically via VBA this apparently results in an error 5981.

answered Sep 16, 2016 at 12:01

Mill's user avatar

MillMill

1106 bronze badges

The error is because when you open the word template the view is protected.
Solution: disable protected view in microsotf word
Go to options, trusted center, protected view disable

answered Jun 7, 2017 at 23:48

walter's user avatar

  • Remove From My Forums
  • Question

  • I embedded a word template into an excel sheet to be used as a template for generating a report that gets filled with data from excel. The purpose of the VBA is to open the embedded word document and save it as a new file name to the same location in order
    not to make changes to the template. I then opens that saved copy and fills in the excel data. The macro works fine on windows, but it only runs once on a mac. The second time you run it you get «error 5981». If I Save the Excel file, close it and
    then open it again, the macro will run. Anybody see anything wrong with the code? Seems like Im not releasing something if restarting excel fixes the problem. The second time I run it it stops at the following line:

    wdApp.ActiveDocument.SaveAs Filename:=file_path2

    file path 2 is linked to a cell with the following equation: =LEFT(CELL(«filename»),FIND(«[«,CELL(«filename»))-1)&»Enterprise «&’Model Inputs’!D7&TEXT((TODAY()),»mmddyyyy»)&».doc»

    Sub GenerateReport()

    Dim wdApp As Object

    Dim wdDoc As Object

    Dim wb As Excel.Workbook

    Dim xlName As Excel.Name

    Application.ScreenUpdating = False        

    Const wdGoToAbsolute As Integer = 1

    Const wdGoToLine As Integer = 3

    'Define WorkbookSet wb = ActiveWorkbook

    On Error GoTo ErrorHandler                

    'Open Template in word   

    wd = Sheets("Hidden Data").Shapes("Object 2").OLEFormat.Verb(Verb:=xlVerbOpen)   

    Set wdApp = GetObject(, "Word.Application")   

    Set wdDoc = wdApp.Documents(1)    

    Worksheets("Hidden Data").Range("B6").Select   

    file_path = ActiveCell.ValueWorksheets("Hidden Data").Range("B5").Select   

    file_path2 = ActiveCell.Value    

    wdApp.ActiveDocument.SaveAs

    Filename:=file_path2wdApp.ActiveDocument.Range.SelectwdApp.ActiveDocument.CloseSet

    wdDoc = NothingSet

    wdApp = Nothing

    Set wd = Nothing

    'Open and Activate new copy of WordSet

    wdApp = GetObject(, "Word.Application")

    Set wdDoc = wdApp.Documents.Open(file_path2) 

    'wdApp.Visible = False

    Set wdDoc = wdApp.ActiveDocument    

    More Code below……………………………………………………………………………………………………………………………

    • Edited by

      Tuesday, July 29, 2014 6:02 AM
      formatting

Answers

  • You might try to re-arrange your code, as it now an one-liner.

    Anyways, the error message implies that your template might be corrupted, check this thread out:

    http://support.microsoft.com/kb/247028

    Hope this helps,


    Daniel van den Berg | Washington, USA | «Anticipate the difficult by managing the easy»

    • Proposed as answer by
      Calvin_Gao
      Friday, February 17, 2012 8:37 AM
    • Marked as answer by
      Calvin_Gao
      Tuesday, February 28, 2012 8:37 AM

I’m getting this error message: «Run-time error 5981. Method ‘Add’ of object ‘Documents’ failed.» This happens when I’m creating a new Word document using a template. The code is posted below and worked fine until the second user in the 2016 version started to use it. It works fine for all 2013 users that are using the older version of the Word template. The error shows up when it gets to the Set wdDoc = wdApp… line below.

Public wdDoc As Word.Document
QuoteDirectory = "R:\PartsQuotes\"
QuoteTemplate = "QuoteTemplate.dot" 'template used for 2013 users
If Application.Version = "16.0" Then QuoteTemplate = QuoteTemplate2016.dotx"
Set wdApp = CreateObject("Word.Application") 'Create an instance of word
Set wdDoc = wdApp.Documents.Add(QuoteDirectory & QuoteTemplate) 'Open word file
wdApp.Visible = True

I need to do a bunch more things with the Word document after it is created which is why I need to create it as a Word.Document. I can get around the error message by creating a second template for the second 2016 user. However, it would be much better to have a common shared template for all users.

Deduplicator's user avatar

Deduplicator

44.7k7 gold badges67 silver badges118 bronze badges

asked Jun 16, 2016 at 11:53

Russ Verbrugge's user avatar

17

A lazier solution can be :

Dim wdDoc As Word.Document
Set wdDoc = GetObject("R:\PartsQuotes\QuoteTemplate.dot", "Word.Application") 
wdDoc.Application.Visible = True

This will open a new document based on the template in the current Word instance or will open new Word application if none open.

Or to try the .dotx template first:

Dim wdDoc As Word.Document
On Error Resume Next
Set wdDoc = GetObject("R:\PartsQuotes\QuoteTemplate2016.dotx", "Word.Application") 
If Err.Number <> 0 Then 
    Set wdDoc = GetObject("R:\PartsQuotes\QuoteTemplate.dot", "Word.Application") 
End If
If not wdDoc Is Nothing Then wdDoc.Application.Visible = True
On Error GoTo 0 ' optional to reset the error handler

Also note that *x files can be opened starting with Office 2007 where .Application.Version = "12.0"

answered Sep 16, 2016 at 14:28

Slai's user avatar

SlaiSlai

22.2k5 gold badges45 silver badges53 bronze badges

1

My own Excel application opens a Word template.

Error 5981 is provoked when calling this statement:

Set oTemplate = moWordApp.Documents.Add(template:=sTemplate, Visible:=True)

The error may also be triggered when opening an existing Word document:

moWordApp.Documents.Open(FileName:=...

In my situation the cause of error 5981 was that the Word-template was not a trusted document.
When opening the Word-template manually, it was opened in protected view. When opening the template automatically via VBA this apparently results in an error 5981.

answered Sep 16, 2016 at 13:57

Mill's user avatar

MillMill

1106 bronze badges

2

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Ошибка 5879 газель некст
  • Ошибка 5p3 на котле аристон как исправить
  • Ошибка 5981 мерседес w164
  • Ошибка 5854 мерседес атего
  • Ошибка 5870 мерседес

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии