Vba runtime error 5941

При попытке использовать Microsoft Visual Basic for Applications (VBA) для изменения свойств документа появляется одно из приведенных ниже сообщений об ошибке.

Проблема

При попытке использовать Microsoft Visual Basic for Applications (VBA) для изменения свойств документа появляется одно из приведенных ниже сообщений об ошибке.

Ошибка при выполнении ‘4248’:

Команда недоступна, так как нет открытых документов

Ошибка при выполнении ‘4605’:
Метод или свойство недоступны, поскольку окно документа не активно

или

Ошибка при выполнении ‘5941’:
Запрашиваемый номер семейства не существует

Причина

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

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

Временное решение

Корпорация Microsoft предлагает примеры программного кода только для иллюстрации и не предоставляет явных или подразумеваемых гарантий относительно их корректной работы в конкретных случаях и в пользовательских приложениях. Примеры в данной статье рассчитаны на пользователя, имеющего достаточный уровень знаний соответствующего языка программирования, а также необходимых средств разработки и отладки. Специалисты служб технической поддержки Microsoft могут пояснить назначение тех или иных конструкций кода в конкретном примере, но модификация примеров и их адаптация к задачам разработчика не поддерживается. Если вам требуется дополнительная консультация по вопросам программирования, вы можете обратиться в службу консалтинга Microsoft или связаться с сертифицированными партнерами компании Microsoft. Дополнительную информацию о партнерах корпорации Microsoft можно найти в Интернете по следующему адресу:

http://www.microsoft.com/partner/referral/ За дополнительной информацией обратитесь к веб-узле корпорации Microsoft по адресу:

http://support.microsoft.com/default.aspx?scid=fh;RU;CNTACTMSЗа дополнительной информацией об использовании приведенных в этой статье примеров обратитесь к следующей статье Microsoft Knowledge Base:

290140 How to Run Sample Code from Knowledge Ниже приведен пример макроса на языке Visual Basic for Applications для изменения значения поля Заголовок в диалоговом окне Свойства. Пример содержит специальный программный код для перехвата ошибок на случай, если нет открытых документов, и вывода соответствующего сообщения.

Sub ChangeDocProperties()

On Error GoTo ErrHandler
ActiveDocument.BuiltInDocumentProperties("Title") = "My Title"
Exit Sub

ErrHandler:
If Err <> 0 Then
'
' Display an error message.
'
MsgBox Err.Description
'
' Clear the error.
'
Err.Clear
Resume Next

End If

End Sub

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

  • Перехват ошибок, если нет открытых документов

    и

  • Создание нового документа при перехвате ошибки

    и

  • Возобновление нормальной работы в строке, вызвавшей появление ошибки

Sub ChangeDocProperties()

On Error GoTo ErrHandler
ActiveDocument.BuiltInDocumentProperties("Title") = "My Title"
Exit Sub

ErrHandler:
If Err <> 0 Then
'
' Add a document.
'
Documents.Add
'
' Clear the error.
'
Err.Clear
'
' Run the code that caused the error.
'
Resume

End If

End Sub

Ссылки

Для получения помощи по работе с Visual Basic обратитесь к следующей статье Microsoft Knowledge Base:

305326 Programming Resources for Visual Basic for Applications

Нужна дополнительная помощь?

Содержание

  1. При попытке использовать VBA для изменения свойств документа появляется сообщение об ошибке при выполнении 4248, 4605 или 5941
  2. Проблема
  3. Причина
  4. Временное решение
  5. Ссылки
  6. You receive run-time error 4248, 4605 or 5941 when you try to change properties on an unopened document in Word
  7. Symptoms
  8. Cause
  9. Workaround
  10. References
  11. You receive run-time error 4248, 4605 or 5941 when you try to change properties on an unopened document in Word
  12. Symptoms
  13. Cause
  14. Workaround
  15. References
  16. You receive run-time error 4248, 4605 or 5941 when you try to change properties on an unopened document in Word
  17. Symptoms
  18. Cause
  19. Workaround
  20. References
  21. Как исправить ошибку Microsoft Word 5941
  22. Сводка «Microsoft Word Error 5941
  23. Что вызывает ошибку 5941 во время выполнения?
  24. Распространенные сообщения об ошибках в Microsoft Word Error 5941
  25. Microsoft Word Error 5941 Истоки проблем

При попытке использовать VBA для изменения свойств документа появляется сообщение об ошибке при выполнении 4248, 4605 или 5941

Проблема

При попытке использовать Microsoft Visual Basic for Applications (VBA) для изменения свойств документа появляется одно из приведенных ниже сообщений об ошибке.

Ошибка при выполнении ‘4248’:

Команда недоступна, так как нет открытых документов

Ошибка при выполнении ‘4605’:
Метод или свойство недоступны, поскольку окно документа не активно

Ошибка при выполнении ‘5941’:
Запрашиваемый номер семейства не существует

Причина

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

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

Временное решение

Корпорация Microsoft предлагает примеры программного кода только для иллюстрации и не предоставляет явных или подразумеваемых гарантий относительно их корректной работы в конкретных случаях и в пользовательских приложениях. Примеры в данной статье рассчитаны на пользователя, имеющего достаточный уровень знаний соответствующего языка программирования, а также необходимых средств разработки и отладки. Специалисты служб технической поддержки Microsoft могут пояснить назначение тех или иных конструкций кода в конкретном примере, но модификация примеров и их адаптация к задачам разработчика не поддерживается. Если вам требуется дополнительная консультация по вопросам программирования, вы можете обратиться в службу консалтинга Microsoft или связаться с сертифицированными партнерами компании Microsoft. Дополнительную информацию о партнерах корпорации Microsoft можно найти в Интернете по следующему адресу:

http://www.microsoft.com/partner/referral/ За дополнительной информацией обратитесь к веб-узле корпорации Microsoft по адресу:

http://support.microsoft.com/default.aspx?scid=fh;RU;CNTACTMSЗа дополнительной информацией об использовании приведенных в этой статье примеров обратитесь к следующей статье Microsoft Knowledge Base:

290140 How to Run Sample Code from Knowledge Ниже приведен пример макроса на языке Visual Basic for Applications для изменения значения поля Заголовок в диалоговом окне Свойства. Пример содержит специальный программный код для перехвата ошибок на случай, если нет открытых документов, и вывода соответствующего сообщения.

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

Перехват ошибок, если нет открытых документов

Создание нового документа при перехвате ошибки

Возобновление нормальной работы в строке, вызвавшей появление ошибки

Ссылки

Для получения помощи по работе с Visual Basic обратитесь к следующей статье Microsoft Knowledge Base:

305326 Programming Resources for Visual Basic for Applications

Источник

You receive run-time error 4248, 4605 or 5941 when you try to change properties on an unopened document in Word

Symptoms

When you try to use Microsoft Visual Basic for Applications (VBA) to change the properties of a document, you may receive one of the following error messages:

Run-time error ‘4248’:

This command is not available because no document is open.

Run-time error ‘4605’:
This method or property is not available because a document window is not active.

Run-time error ‘5941’:
The requested member of the collection does not exist.

Cause

This problem may occur if you do not have a document open, or if the document that you are referencing is not open. Word can only change the properties of an open (or visible) document.

Note These error messages may also appear if you open the document with the Visible property set to
False.

Workaround

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.
If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:

For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS
For additional information about how to use the sample code that is included in this article, click the following article number to view the article in the Microsoft Knowledge Base:

290140 OFFXP: How to Run Sample Code from Knowledge Base Articles

The following sample VBA macros demonstrate how to change the value of the Title field in the
Properties dialog box. The following sample also includes code to trap the error, in case there are no documents open, and to display a message:

The following sample macro includes code that will do the following:

Trap the error, in case there are no documents open.

In the error trap, create a new document.

Resume execution at the line that caused the error.

References

For additional information about how to get help with VBA, click the following article number to view the article in the Microsoft Knowledge Base:

305326 OFFXP: Programming Resources for Visual Basic for Applications

Источник

You receive run-time error 4248, 4605 or 5941 when you try to change properties on an unopened document in Word

Symptoms

When you try to use Microsoft Visual Basic for Applications (VBA) to change the properties of a document, you may receive one of the following error messages:

Run-time error ‘4248’:

This command is not available because no document is open.

Run-time error ‘4605’:
This method or property is not available because a document window is not active.

Run-time error ‘5941’:
The requested member of the collection does not exist.

Cause

This problem may occur if you do not have a document open, or if the document that you are referencing is not open. Word can only change the properties of an open (or visible) document.

Note These error messages may also appear if you open the document with the Visible property set to
False.

Workaround

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.
If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:

For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS
For additional information about how to use the sample code that is included in this article, click the following article number to view the article in the Microsoft Knowledge Base:

290140 OFFXP: How to Run Sample Code from Knowledge Base Articles

The following sample VBA macros demonstrate how to change the value of the Title field in the
Properties dialog box. The following sample also includes code to trap the error, in case there are no documents open, and to display a message:

The following sample macro includes code that will do the following:

Trap the error, in case there are no documents open.

In the error trap, create a new document.

Resume execution at the line that caused the error.

References

For additional information about how to get help with VBA, click the following article number to view the article in the Microsoft Knowledge Base:

305326 OFFXP: Programming Resources for Visual Basic for Applications

Источник

You receive run-time error 4248, 4605 or 5941 when you try to change properties on an unopened document in Word

Symptoms

When you try to use Microsoft Visual Basic for Applications (VBA) to change the properties of a document, you may receive one of the following error messages:

Run-time error ‘4248’:

This command is not available because no document is open.

Run-time error ‘4605’:
This method or property is not available because a document window is not active.

Run-time error ‘5941’:
The requested member of the collection does not exist.

Cause

This problem may occur if you do not have a document open, or if the document that you are referencing is not open. Word can only change the properties of an open (or visible) document.

Note These error messages may also appear if you open the document with the Visible property set to
False.

Workaround

Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This article assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs.
If you have limited programming experience, you may want to contact a Microsoft Certified Partner or Microsoft Advisory Services. For more information, visit these Microsoft Web sites:

For more information about the support options that are available and about how to contact Microsoft, visit the following Microsoft Web site:http://support.microsoft.com/default.aspx?scid=fh;EN-US;CNTACTMS
For additional information about how to use the sample code that is included in this article, click the following article number to view the article in the Microsoft Knowledge Base:

290140 OFFXP: How to Run Sample Code from Knowledge Base Articles

The following sample VBA macros demonstrate how to change the value of the Title field in the
Properties dialog box. The following sample also includes code to trap the error, in case there are no documents open, and to display a message:

The following sample macro includes code that will do the following:

Trap the error, in case there are no documents open.

In the error trap, create a new document.

Resume execution at the line that caused the error.

References

For additional information about how to get help with VBA, click the following article number to view the article in the Microsoft Knowledge Base:

305326 OFFXP: Programming Resources for Visual Basic for Applications

Источник

Как исправить ошибку Microsoft Word 5941

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

Сводка «Microsoft Word Error 5941

Это наиболее распространенное условие «Microsoft Word Error 5941», известное как ошибка времени выполнения (ошибка). Программисты работают через различные уровни отладки, пытаясь убедиться, что Microsoft Word как можно ближе к безошибочным. Ошибки, такие как ошибка 5941, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.

В выпуске последней версии Microsoft Word может возникнуть ошибка, которая гласит: «Microsoft Word Error 5941». Сообщение об этой ошибке 5941 позволит разработчикам обновить свое приложение и исправить любые ошибки, которые могут вызвать его. Затем Microsoft Corporation будет иметь знания, чтобы исследовать, как и где устранить проблему. Таким образом, в этих случаях разработчик выпустит обновление программы Microsoft Word, чтобы исправить отображаемое сообщение об ошибке (и другие сообщенные проблемы).

Что вызывает ошибку 5941 во время выполнения?

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

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

Утечка памяти «Microsoft Word Error 5941» — при утечке памяти Microsoft Word это может привести к медленной работе устройства из-за нехватки системных ресурсов. Потенциальные триггеры могут быть бесконечным циклом, что приводит к тому, что работа программы запускается снова и снова.

Ошибка 5941 Logic Error — «логическая ошибка», как говорят, генерируется, когда программное обеспечение получает правильный ввод, но генерирует неверный вывод. Обычные причины этой проблемы связаны с ошибками в обработке данных.

Большинство ошибок Microsoft Word Error 5941 являются результатом отсутствия или повреждения версии файла, установленного Microsoft Word. Возникновение подобных проблем является раздражающим фактором, однако их легко устранить, заменив файл Microsoft Corporation, из-за которого возникает проблема. В некоторых случаях реестр Windows пытается загрузить файл Microsoft Word Error 5941, который больше не существует; в таких ситуациях рекомендуется запустить сканирование реестра, чтобы исправить любые недопустимые ссылки на пути к файлам.

Распространенные сообщения об ошибках в Microsoft Word Error 5941

Частичный список ошибок Microsoft Word Error 5941 Microsoft Word:

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

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

Microsoft Word Error 5941 Истоки проблем

Проблемы Microsoft Word Error 5941 вызваны поврежденным или отсутствующим Microsoft Word Error 5941, недопустимыми ключами реестра, связанными с Microsoft Word, или вредоносным ПО.

В первую очередь, проблемы Microsoft Word Error 5941 создаются:

  • Недопустимая или поврежденная запись Microsoft Word Error 5941.
  • Файл Microsoft Word Error 5941 поврежден от вирусной инфекции.
  • Microsoft Word Error 5941 злонамеренно или ошибочно удален другим программным обеспечением (кроме Microsoft Word).
  • Microsoft Word Error 5941 конфликтует с другой программой (общим файлом).
  • Поврежденная установка или загрузка Microsoft Word (Microsoft Word Error 5941).

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

Источник

  • Remove From My Forums
  • Question

  • I have looked at some of the explanations and suggested cures but they are not simple enough for me.  I am trying to make a macro which will insert my address etc on a blank document.  I have the address layout stored in Quick Parts, so having
    brought up a blank normal document on screen, I usually go to Quick Parts and insert the block and then back to Home before proceeding.  I wanted to have a Quick Access macro which would do that.  So I am bringing up the blank, going into record
    Macro and assigning to button and recording then to Quick Parts, selecting the address, Insert, and then back to Home, before Stop Recording.    However, when I try to run the macro, I get the 5941 message each and every time.  On debug
    the whole macro is highlighted.

    I did make a successful macro for PrintPage which was fine and I use it all the time.  I have Windows 7 64 bit and Word 2010 Office and Student.

Answers

  • Sounds right. Like this?

    Sub Macro1()

    ‘ Macro1 Macro

    Templates.LoadBuildingBlocks 
        Application.Templates( _
            «C:UsersJosephineAppDataRoamingMicrosoftDocument Building Blocks103314Building Blocks.dotx» _
            ).BuildingBlockEntries(«HomeAddress»).Insert Where:=Selection.Range, _
            RichText:=True
    End Sub


    Enjoy,
    Tony
    www.WordArticles.com

    • Marked as answer by

      Monday, July 18, 2011 6:52 AM

  • Hi «Boots»

    I was going to suggest the same thing as Tony and am as surprised as he that it didn’t work. The next step would be to narrow down whether the «missing member» of the collection refers to the template or to the Building Block entry. So let’s break the recorded
    macro down into smaller pieces and see exactly where the problem is coming from. Try something like this and tell us which line gets highlighted:

    Sub Macro1()
      Dim tmpl as Word.Template
    
      Application.Templates.LoadBuildingBlocks 
      Set tmpl = Application.Templates( _
        "C:UsersJosephineAppDataRoamingMicrosoftDocument Building Blocks103314Building Blocks.dotx")
     
       tmpl.BuildingBlockEntries("HomeAddress").Insert Where:=Selection.Range, _
        RichText:=True
    End Sub
    

    Cindy Meister, VSTO/Word MVP

    • Marked as answer by
      Calvin_Gao
      Monday, July 18, 2011 6:51 AM

  • Hi «Boots»

    I’m amazed that just pulling the stuff apart worked. Word never ceases to amaze me…

    In order to give a macro a different name, simply change what appears after the word «Sub». To name the macro InsertMyAddress, for example, change the line

      Sub Macro1()

    to

      Sub InsertMyAddress()

    To assign this to your Quick Access Toolbar (QAT), click on the arrow that points down at the very end of the QAT. Choose «More commands…» This should open the File/Options dialog box at the correct «tab». From the dropdown list at the top left choose
    «Macros». Click on the macro, then click the button to ADD it to the list on the right. If you want to see a different icon, click on the macro in the list on the right, then click «Modify». There you can choose a picture and change the «Display name».

    (I’m looking at Word 2007, where the names of things are a bit different. That’s why I’m not giving you the exact menu names — I don’t want to confuse you!)


    Cindy Meister, VSTO/Word MVP

    • Marked as answer by
      Calvin_Gao
      Monday, July 18, 2011 6:51 AM

 

ddmitriy

Пользователь

Сообщений: 5
Регистрация: 01.10.2014

#1

21.06.2017 17:17:09

Добрый день.
При вставке фотографии в шаблон Word выскакивает ошибка «5941 Запрашиваемый номер семейства не существует»

Код
With WD
Picture_count = Picture_count + 1
    .Bookmarks("pic1").Range.Select
    FolderPic = Replace(ThisWorkbook.FullName, ThisWorkbook.Name, "Pic1")
    Dim coll As Collection
    If Dir(FolderPic, vbDirectory) = "" Then
        MsgBox "No Folder Pic1" & folder$ & "»", vbCritical, "No Folder "
        GoTo pict_1
    End If
    Set coll = FilenamesCollection(FolderPic, ".jpg")
    For i = 1 To coll.Count
          
       WA.Selection.InlineShapes.AddPicture Filename:=coll.Item(i)
       WA.Selection.TypeParagraph
    Next i
pict_1: End With

Ошибка указывает на строку.

Код
.Bookmarks("pic1").Range.Select

Закладки проверил, всё в норме. Подскажите что ещё может быть не так.

Спасибо.

 

The_Prist

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

Ответ один — его действительно не существует. Если Вы в одну и ту же закладку в цикле что-то пытаетесь записать, то это вполне возможно, т.к. после первой записи закладка как правило удаляется.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

R Dmitry

Пользователь

Сообщений: 3103
Регистрация: 22.12.2012

Excel,MSSQL,Oracle,Qlik

#3

21.06.2017 17:34:49

покажите весь код
возможно не правильно обращаетесь к документу либо обращаетесь к неактивному документу с командой select
попробуйте

Код
wd.Activate
 wd.Bookmarks("pic1").Range.Select

Спасибо

 

R Dmitry

Пользователь

Сообщений: 3103
Регистрация: 22.12.2012

Excel,MSSQL,Oracle,Qlik

#4

21.06.2017 17:49:06

Цитата
The_Prist написал:
т.к. после первой записи закладка как правило удаляется.

——
Если использовать не диапазон (кусок) текста в закладке, а положение курсора, то ничего не удаляется :))

Спасибо

 

The_Prist

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

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

Изменено: The_Prist21.06.2017 17:50:14

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

R Dmitry

Пользователь

Сообщений: 3103
Регистрация: 22.12.2012

Excel,MSSQL,Oracle,Qlik

#6

21.06.2017 17:51:01

The_Prist,  Поэтому и прошу старттопика показать весь кусок кода. Что там у него за WD только он знает :)

Спасибо

 

ddmitriy

Пользователь

Сообщений: 5
Регистрация: 01.10.2014

#7

21.06.2017 17:54:07

R Dmitry? не помогло.
Весь код:

Скрытый текст

 

The_Prist

Пользователь

Сообщений: 13997
Регистрация: 15.09.2012

Профессиональная разработка приложений для MS Office

#8

21.06.2017 17:54:37

Цитата
R Dmitry написал:
Если использовать не диапазон

если кусок — да, не удалится. Но у ТС-а же не так :)

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

roslova

0 / 0 / 0

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

Сообщений: 3

1

Word

11.12.2018, 21:03. Показов 25738. Ответов 4

Метки vba, макрос (Все метки)


Всем привет. я не программист и у меня такая проблема: писала довольно простой макрос для создания формулы с автоматической нумерацией в ворде (чтобы формула не «съезжала» влево). вроде создаю сам макрос, но когда хочу добавить его на панель быстрого доступа, вылезает ошибка: «ошибка 5941: «запрашиваемый номер семейства не существует».

текст в VisualB такой:

Visual Basic
1
2
3
4
5
6
7
8
Sub формулка()
'
' формулка Макрос
'
'
    ActiveDocument.AttachedTemplate.BuildingBlockEntries( _
        "формула с нумерацией").Insert Where:=Selection.Range, RichText:=True
End Sub

и я понятия не имею, что надо исправить…
помогите пожалуйста

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



0



oh my god

1454 / 793 / 161

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

Сообщений: 2,307

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

11.12.2018, 21:08

2

судя по всему вы какой -то шаблон пытаетесь запустить
но скорей всего вы имя неверное ввели «формула с нумерацией»
убедитесь что оно у вас в шабл. есть



0



74 / 7 / 2

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

Сообщений: 72

11.12.2018, 21:13

3

https://support.microsoft.com
Проблема возникает, когда нет открытых документов или не открыт документ, на который сделана ссылка. В программе Word предусмотрено изменение свойств только открытых документов.
Примечание. Такие сообщения об ошибках могут появиться также в том случае, если открыт документ, у которого свойство Видимый имеет значение Ложь.



0



oh my god

1454 / 793 / 161

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

Сообщений: 2,307

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

11.12.2018, 21:16

4

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

Видимый имеет значение Ложь.

защиту от дурака надо убрать ))



0



0 / 0 / 0

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

Сообщений: 3

12.12.2018, 08:52

 [ТС]

5

вот по этому видео пыталась сделать нумерацию. не вышло. сама формула в уравнениях имеется, а в маркрос ее не удается сделать. спасибо всем за наводки по решению проблемы



0



  1. Aug 30th, 2010, 11:28 AM


    #1

    NewVBer is offline

    Thread Starter


    Junior Member


    Resolved [RESOLVED] Runtme Error 5941

    Hello —

    I have created a Word template that will be used to generate a new document and I’m trying to populate a dropdown list with data from an Access table. I’ve tried different variations on the code but keep receiving errors. Specifically, I’m receiving the Runtime error «5941» The requested member of the collection does not exist.

    Below is the code and I’ve highlighted in red the line where the error occurs. I’ve tried using FormFields, I’ve tried ContentControls but cannot get it to work. I’ve checked the reference libraries and believe that I am using the correct ones. I’m running Word & Access 2007, and VBA 6.5. I’m using the followiing object libraries: Word & Access 12.0, Forms 2.0. I’m still pretty green at this so I would greatly appreciate any help…I’m sure it’s something dumb that I’m just missing so thank you for your patience and assistance.

    Code:

    Dim cnt As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim strDB As String
    Set cn = New ADODB.Connection
    'Set string path to database'
        strDB = "C:---"
        'Open the database to retrieve data
    cnt.Open "Provider=Microsoft.Ace.OLEDB.12.0;" & _
    "Data Source=" & strDB & ";"
    'Open recordset based on SelectedProjects Table
    rst.Open "Select * From SelectedProjects", cnt
    rst.MoveFirst
    Windows("Template1").Activate
    With ActiveDocument.FormFields("Dropdown1").DropDown.ListEntries
    .Clear
    Do
    .Add rst![ProjectName]
    rst.MoveNext
    Loop Until rst.EOF
    
    End With


  2. Aug 30th, 2010, 04:39 PM


    #2

    Re: Runtme Error 5941

    is the document containing the dropdown called template1?

    i tested your code without error, so i can only assume that the active document does not contain a dropdown named dropdown1
    try documents(«templte1»).activate
    or better
    With Documents(«template1»).FormFields(«Dropdown1»).DropDown.ListEntries

    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. Aug 30th, 2010, 08:30 PM


    #3

    NewVBer is offline

    Thread Starter


    Junior Member


    Re: Runtime Error 5941

    It still didn’t work and I am at a loss…I tried changing it as you recommended but I’m still getting the Runtime error. I double checked and even changed the file name and dropdown name to make sure that I was using the correct names (see below). I’m still getting the error in the same place. I tried modifying the code to

    With ActiveDocument.ContentControls(«Projects»).DropdownListEntries

    using the ContentControls instead of FormFields but I still get the same runtime error (5941) with the above line. Maybe I’m missing something there??

    I’m in design mode and I click on «Insert a dropdown list content control». Could that be the issue?

    Code:

    Dim cnt As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim strDB As String
    Set cn = New ADODB.Connection
    'Set string path to database'
        strDB = "C:usersstacydocumentsmy data sourcesPEI.accdb"
        'Open the database to retrieve data
    cnt.Open "Provider=Microsoft.Ace.OLEDB.12.0;" & _
    "Data Source=" & strDB & ";"
    'Open recordset based on SelectedProjects Table
    rst.Open "Select * From SelectedProjects", cnt
    rst.MoveFirst
    Windows("Item 7 - Resume Template Test").Activate
    With ActiveDocument.FormFields("Projects").DropDown.ListEntries
    .Clear
    Do
    .Add rst![ProjectName]
    rst.MoveNext
    Loop Until rst.EOF
    
    End With


  4. Aug 30th, 2010, 08:41 PM


    #4

    NewVBer is offline

    Thread Starter


    Junior Member


    Unhappy Re: Runtme Error 5941

    Here’s the code I tried as you recommended…then I replaced formfields with contentcontrols. Either way I do it, I’m still receiving the same error. I’ve checked and rechecked the file name and name of the dropdown. I’ve even manually added text the dropdown to make sure that it worked. I’m not sure what else to try??

    Code:

    Documents("Item 7 - Resume Template - Test").Activate
    With Documents("Item 7 - Resume Template - Test").ContentControls("Projects").DropdownListEntries


  5. Aug 31st, 2010, 03:05 AM


    #5

    Re: Runtme Error 5941

    post a sample document that demonstrates the problem

    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


  6. Sep 27th, 2010, 11:45 AM


    #6

    NewVBer is offline

    Thread Starter


    Junior Member


    Re: Runtme Error 5941

    Sorry for the delay…I figured out a work around for this. I have a different issue now so I will mark this as resolved and put out a new post. Thanks so much for all of your help.


Понравилась статья? Поделить с друзьями:
  • Vba игнорировать ошибки
  • Vba runtime error 5017
  • Vba если ошибка то дальше
  • Vba runtime error 462 word
  • Vba runtime error 429 activex component can t create object