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:
Microsoft Certified Partners — https://partner.microsoft.com/global/30000104
Microsoft Advisory Services — http://support.microsoft.com/gp/advisoryservice
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:
Sub ChangeDocProperties()On Error GoTo ErrHandler
ActiveDocument.BuiltInDocumentProperties("Title") = "My Title"
Exit SubErrHandler:
If Err <> 0 Then
'
' Display an error message.
'
MsgBox Err.Description
'
' Clear the error.
'
Err.Clear
Resume NextEnd If
End Sub
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.
Sub ChangeDocProperties()On Error GoTo ErrHandler
ActiveDocument.BuiltInDocumentProperties("Title") = "My Title"
Exit SubErrHandler:
If Err <> 0 Then
'
' Add a document.
'
Documents.Add
'
' Clear the error.
'
Err.Clear
'
' Run the code that caused the error.
'
ResumeEnd If
End Sub
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
Need more help?
roslova 0 / 0 / 0 Регистрация: 11.12.2018 Сообщений: 3 |
||||
1 |
||||
Word 11.12.2018, 21:03. Показов 25736. Ответов 4 Метки vba, макрос (Все метки)
Всем привет. я не программист и у меня такая проблема: писала довольно простой макрос для создания формулы с автоматической нумерацией в ворде (чтобы формула не «съезжала» влево). вроде создаю сам макрос, но когда хочу добавить его на панель быстрого доступа, вылезает ошибка: «ошибка 5941: «запрашиваемый номер семейства не существует». текст в VisualB такой:
и я понятия не имею, что надо исправить…
__________________
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
0 |
oh my god 1454 / 793 / 161 Регистрация: 05.01.2016 Сообщений: 2,307 Записей в блоге: 8 |
|
11.12.2018, 21:16 |
4 |
Видимый имеет значение Ложь. защиту от дурака надо убрать ))
0 |
0 / 0 / 0 Регистрация: 11.12.2018 Сообщений: 3 |
|
12.12.2018, 08:52 [ТС] |
5 |
вот по этому видео пыталась сделать нумерацию. не вышло. сама формула в уравнениях имеется, а в маркрос ее не удается сделать. спасибо всем за наводки по решению проблемы
0 |
ddmitriy Пользователь Сообщений: 5 |
#1 21.06.2017 17:17:09 Добрый день.
Ошибка указывает на строку.
Закладки проверил, всё в норме. Подскажите что ещё может быть не так. Спасибо. |
||||
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
Ответ один — его действительно не существует. Если Вы в одну и ту же закладку в цикле что-то пытаетесь записать, то это вполне возможно, т.к. после первой записи закладка как правило удаляется. Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
R Dmitry Пользователь Сообщений: 3103 Excel,MSSQL,Oracle,Qlik |
#3 21.06.2017 17:34:49 покажите весь код
|
|||
R Dmitry Пользователь Сообщений: 3103 Excel,MSSQL,Oracle,Qlik |
#4 21.06.2017 17:49:06
——
|
|||
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
Дмитрий, в данном случае активация избыточна, т.к. идет обращение к закладкам конкретного документа: WD. Поэтому озвученная ошибка не может возникнуть по этой причине. Если бы активен был другой документ, то была бы другая ошибка. Изменено: The_Prist — 21.06.2017 17:50:14 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
R Dmitry Пользователь Сообщений: 3103 Excel,MSSQL,Oracle,Qlik |
#6 21.06.2017 17:51:01 The_Prist, Поэтому и прошу старттопика показать весь кусок кода. Что там у него за WD только он знает
|
|
ddmitriy Пользователь Сообщений: 5 |
#7 21.06.2017 17:54:07 R Dmitry? не помогло.
|
|
The_Prist Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
#8 21.06.2017 17:54:37
если кусок — да, не удалится. Но у ТС-а же не так Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
- 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
-
Marked as answer by
-
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
-
Marked as answer by
-
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
-
Marked as answer by
When running the macro I am getting the following error:
«Runtime Error ‘5941’ The Requested Member of Collection Does Not Exist»
The line below is highlighted in Yellow; This Macro works on the majority of users and the error has only been reported off two users.
Windows(DestTemplateName).Document.Bookmarks("fCustomer").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fCust").Range.Fields(1).Result.Text
Any Help Would Be Much Appreciated.
Sub PopulateBookingForm()
Dim SourceTemplateName As String, DestTemplateName As String
' Set Method Statement Name
SourceTemplateName = ActiveDocument.Name
' Open Heavy Cranes ICO Booking Form
ChangeFileOpenDirectory "\SERVERSHAREHCDHCD GeneralTemplates"
Documents.Open FileName:= _
"\SERVERSHAREHCDHCD GeneralTemplatesHeavy Cranes ICO Booking Form.docx", _
ConfirmConversions:=False, ReadOnly:=False, AddToRecentFiles:=False, _
PasswordDocument:="", PasswordTemplate:="", Revert:=False, _
WritePasswordDocument:="", WritePasswordTemplate:="", Format:= _
wdOpenFormatAuto, XMLTransform:=""
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
' Set Haulage Booking Form Document Name
DestTemplateName = ActiveDocument.Name
' ### START FIND AND REPLACE
' Populate Customer(Client)
Windows(DestTemplateName).Document.Bookmarks("fCustomer").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fCust").Range.Fields(1).Result.Text
' Populate Version
Windows(DestTemplateName).Document.Bookmarks("fVersion").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fRevision").Range.Fields(1).Result.Text
' Populate Entered Onto CRM
Windows(DestTemplateName).Document.Bookmarks("fEnteredOntoCRM").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fEnteredOntoCRM").Range.Fields(1).Result.Text
' Populate CRM Opportunity Name
Windows(DestTemplateName).Document.Bookmarks("fCRMOportunityName").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fCRMOportunityName").Range.Fields(1).Result.Text
' Populate Contact Name
Windows(DestTemplateName).Document.Bookmarks("fContactName").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteContact").Range.Fields(1).Result.Text
' Populate Telephone No (Mobile)
If Replace(Windows(SourceTemplateName).Document.Bookmarks("fSiteMobile").Range.Fields(1).Result.Text, ChrW(8194), "") = "" Then
Windows(DestTemplateName).Document.Bookmarks("fTelephoneNo").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteTel").Range.Fields(1).Result.Text
Else
Windows(DestTemplateName).Document.Bookmarks("fTelephoneNo").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteMobile").Range.Fields(1).Result.Text
End If
' Populate Fax No(Email)
Windows(DestTemplateName).Document.Bookmarks("fFaxNo").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteFax").Range.Fields(1).Result.Text
' Populate Site Address
Windows(DestTemplateName).Document.Bookmarks("fSiteAddress").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fSiteAddr").Range.Fields(1).Result.Text
' Populate Duration
Windows(DestTemplateName).Document.Bookmarks("fDuration").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fDuration").Range.Fields(1).Result.Text
' Populate Date of Hire/RFW
Windows(DestTemplateName).Document.Bookmarks("fTimeReadyForWork").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("dt1").Range.Fields(1).Result.Text
Windows(DestTemplateName).Document.Bookmarks("fDayDateOfHire").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("dt1").Range.Fields(1).Result.Text
' Populate Inspector
Windows(DestTemplateName).Document.Bookmarks("fFormCompletedBy").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fACHSiteInspector").Range.Fields(1).Result.Text
Windows(DestTemplateName).Document.Bookmarks("fSiteVisitedBy").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fACHSiteInspector").Range.Fields(1).Result.Text
Windows(DestTemplateName).Document.Bookmarks("fMethodStatementBy").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fACHSiteInspector").Range.Fields(1).Result.Text
' Populate CL
Windows(DestTemplateName).Document.Bookmarks("fCL").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fTermsCL").Range.Fields(1).Result.Text
' Populate CH
Windows(DestTemplateName).Document.Bookmarks("fCH").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fTermsCH").Range.Fields(1).Result.Text
' Populate Wires
Windows(DestTemplateName).Document.Bookmarks("fWires").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryWires").Range.Fields(1).Result.Text
' Populate Web Slings
Windows(DestTemplateName).Document.Bookmarks("fWebSlings").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryWebSlings").Range.Fields(1).Result.Text
' Populate Beams
Windows(DestTemplateName).Document.Bookmarks("fBeams").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryBeams").Range.Fields(1).Result.Text
' Populate Chains
Windows(DestTemplateName).Document.Bookmarks("fChains").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryChains").Range.Fields(1).Result.Text
' Populate Shackles
Windows(DestTemplateName).Document.Bookmarks("fShackles").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryShackles").Range.Fields(1).Result.Text
' Populate Other
Windows(DestTemplateName).Document.Bookmarks("fOther").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fAccessoryOthers").Range.Fields(1).Result.Text
' Populate Job Description
Windows(DestTemplateName).Document.Bookmarks("fJobDescription").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fDescOfWorks").Range.Fields(1).Result.Text & vbNewLine & vbNewLine & Windows(SourceTemplateName).Document.Bookmarks("fOperReqACHL").Range.Fields(1).Result.Text
' Populate Other Information
Windows(DestTemplateName).Document.Bookmarks("fOperationByClient").Range.Fields(1).Result.Text = Windows(SourceTemplateName).Document.Bookmarks("fOperReqClient").Range.Fields(1).Result.Text
' ### END FIND AND REPLACE
' Activate New Document
Windows(DestTemplateName).Activate
End Sub
The Macro Basically Copies Some Text From Fields In The Source Document Over To The Destination Document.
-
Aug 30th, 2010, 11:28 AM
#1
Thread Starter
Junior Member
[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
-
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.ListEntriesi 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 Nextdim 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
-
Aug 30th, 2010, 08:30 PM
#3
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
-
Aug 30th, 2010, 08:41 PM
#4
Thread Starter
Junior Member
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
-
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 Nextdim 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
-
Sep 27th, 2010, 11:45 AM
#6
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.
Номер ошибки: | Ошибка 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).
Продукт Solvusoft
Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
thanks for the reply. I’m not sure the answer to your question, i actually inherited this code from someone who wrote it years ago so i am not familiar with all of it. the functionality is transferring information to the bookmarks in word which are named after named cells in excel.
I had a separate thread that asked about a separate issue, but the thread was closed. if anyone could help me with the formatting issue i am also having, i would appreciate it. thanks so much:
I am trying to import data from excel to word. the excel cells that i want transferred are named and i built out tables in word that have the corresponding «cells» bookmarked.
for the numeric data, i have an issue. some are percentages, some need two decimals, some i would prefer as whole numbers. the issue is that certain items that i would need 2 decimal places for come through as whole number. so 1.15 comes in as 1. 1.2 as 1. .65 as 1, etc…. i inherited the code for this and tried to edit it but had no luck. does anyone know how i can have the formatting change based on how it is displayed in excel? also, is there a certain way i should format in excel so that the data transfers as intended?
I have posted the entire code below:
Code:
Dim oExcel As Object Dim eBook As Object Dim formatCell As String Sub ImportData() Dim ExcelFileName As String Dim Dated As Date ExcelFileName = SelectFile("Excel", "xlsm") If ExcelFileName = "" Then MsgBox "Excel file not selected - Import canceled.", vbInformation: Exit Sub Dim wDoc As Document Set wDoc = ActiveDocument Set oExcel = CreateObject("Excel.Application") Set eBook = oExcel.Workbooks.Open(ExcelFileName) 'oExcel.Visible = True Application.StatusBar = "Please be patient as the data is imported..." Application.ScreenUpdating = False 'On Error GoTo 10 Dim tbl As Table Dim iSource As String Dim fValue As String Dim cl As Cell Dim item As Bookmark Dim itemName As String Dim a As Long For a = wDoc.Bookmarks.Count To 1 Step -1 Set item = wDoc.Bookmarks(a) itemName = item.Name Set cl = item.Range.Cells(1) fValue = RangeValue(itemName) If fValue <> "" Then If IsNumeric(fValue) Then Select Case formatCell Case "Percentage" item.Range.Text = Format(fValue, formatCell) Case "0%" item.Range.Text = Format(fValue, formatCell) Case "0.0%" item.Range.Text = Format(fValue, formatCell) Case "0.00%" item.Range.Text = Format(fValue, formatCell) Case "0.00""x""" item.Range.Text = Format(fValue, "0.00""x""") Case Else item.Range.Text = Format(fValue, "#,##0;(#,##0);"" - """) End Select Else item.Range.Text = fValue End If End If wDoc.Bookmarks.Add itemName, cl.Range Next eBook.Close False oExcel.Quit Application.ScreenUpdating = True Set eSheet = Nothing Set eBook = Nothing Set oExcel = Nothing DoEvents Application.StatusBar = "" MsgBox "Import Completed.", vbInformation Exit Sub 10: eBook.Close False oExcel.Quit Application.ScreenUpdating = True Set eSheet = Nothing Set eBook = Nothing Set oExcel = Nothing MsgBox Err.Description End Sub Private Function SelectFile(FileTypeName As String, FileType As String) As String Dim FD As FileDialog SelectFile = "" Set FD = Application.FileDialog(msoFileDialogFilePicker) With FD .Title = "Select " & FileTypeName & " file" .AllowMultiSelect = False .Filters.Clear .Filters.Add FileTypeName & " File", "*." & FileType End With If FD.Show = -1 Then SelectFile = FD.SelectedItems(1) End If End Function Private Function RangeValue(RangeName As String) As String Dim i As Long Dim RangeToFind As Range Dim str As String Err.Clear On Error Resume Next With eBook For i = 1 To .Sheets.Count str = .Sheets(i).Range(RangeName).Value If Err.Number = 0 Then RangeValue = str formatCell = .Sheets(i).Range(RangeName).NumberFormat Exit For Else Err.Clear End If Next i End With On Error GoTo 0 Err.Clear End Function