Проблема
При попытке использовать 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 SubErrHandler:
If Err <> 0 Then
'
' Display an error message.
'
MsgBox Err.Description
'
' Clear the error.
'
Err.Clear
Resume NextEnd If
End Sub
Приведенный ниже программный код предусмотрен для выполнения следующих целей.
-
Перехват ошибок, если нет открытых документов
и
-
Создание нового документа при перехвате ошибки
и
-
Возобновление нормальной работы в строке, вызвавшей появление ошибки
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
Ссылки
Для получения помощи по работе с Visual Basic обратитесь к следующей статье Microsoft Knowledge Base:
305326 Programming Resources for Visual Basic for Applications
Нужна дополнительная помощь?
Нужны дополнительные параметры?
Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.
В сообществах можно задавать вопросы и отвечать на них, отправлять отзывы и консультироваться с экспертами разных профилей.
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?
Want more options?
Explore subscription benefits, browse training courses, learn how to secure your device, and more.
Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.
SkyFlyStaR 1 / 1 / 0 Регистрация: 16.10.2011 Сообщений: 69 |
||||
1 |
||||
10.04.2013, 19:12. Показов 5918. Ответов 7 Метки нет (Все метки)
oTable — таблица Добавлено через 22 минуты
0 |
Казанский 15139 / 6413 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
||||
10.04.2013, 20:34 |
2 |
|||
А можно выполнить действия
Выделение при этом видно?
0 |
1 / 1 / 0 Регистрация: 16.10.2011 Сообщений: 69 |
|
10.04.2013, 20:53 [ТС] |
3 |
На otable.rows(2).select так реагирует: Отсутствует доступ к отдельным строкам, поскольку таблица имеет ячейки, объединенные по вертикали Это можно как-то обойти? Или при таком редактировании чтение из ячеек таблицы невозможно?
0 |
15139 / 6413 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
|
10.04.2013, 22:00 |
4 |
Форматирование таблиц в WORD
1 |
5471 / 1149 / 50 Регистрация: 15.09.2012 Сообщений: 3,515 |
|
11.04.2013, 07:35 |
5 |
SkyFlyStaR, напишите словесное описание вашей задачи. Если у вас задача большая, то разбейте задачу на части и обсудите пока одну часть. Если на словах сложно объяснить, то сформируйте Word-документ с примерными данными, выложите на Форуме этот документ и на основе этого документа опишите вашу задачу.
0 |
1 / 1 / 0 Регистрация: 16.10.2011 Сообщений: 69 |
|
11.04.2013, 19:15 [ТС] |
6 |
SkyFlyStaR, напишите словесное описание вашей задачи. Если у вас задача большая, то разбейте задачу на части и обсудите пока одну часть. Если на словах сложно объяснить, то сформируйте Word-документ с примерными данными, выложите на Форуме этот документ и на основе этого документа опишите вашу задачу. Нужно считать текст из каждой ячейки 1го столбца таблицы , все просто, но эта ошибка все портит
0 |
Скрипт 5471 / 1149 / 50 Регистрация: 15.09.2012 Сообщений: 3,515 |
||||||||||
11.04.2013, 19:47 |
7 |
|||||||||
Вариант 1 Код работает с первой таблицей на активном документе. Кликните здесь для просмотра всего текста
Вариант 2 Другой вариант. Отличие от первого варианта в том, что макрос должен быстрее работать, т.к. не надо будет проходить по всем ячейкам таблицы. Кликните здесь для просмотра всего текста
Хотя в таком документе (см. вложение) второй вариант неправильно работает. Вложения
2 |
Скрипт 5471 / 1149 / 50 Регистрация: 15.09.2012 Сообщений: 3,515 |
||||
11.04.2013, 20:39 |
8 |
|||
Вариант 3 Отличие от других двух вариантов. Работает в тех случаях, когда «Вариант 2» не работает. По идее быстрее должен работать, чем «Вариант 1», т.к. не просматриваются все ячейки. Кликните здесь для просмотра всего текста
1 |
- Remove From My Forums
-
Question
-
Hi All,
I have a problem with a template which randomly generates the run-time error ‘5941 the requested member of the collection does not exist’. What seemed strange is that it works fine sometimes and others it would generate the error. After much
searching, I have discovered that the code is not executing sequentially (ie. it is essentially executing in a multi-threaded or asynchronous fashion). The code structure looks a like this:Private Sub AutoNew
Some code A
Load Form1
Code for Form1Some Code B
Load Form2
Code for Form2Some Code C
End Sub
Basically, a few simple lines of code execute, then a form is loaded. The user completes the form and then clicks OK. The code in the form then moves around the document inserting text. At the completion of the form code, the cursor is
in the second cell of the last row of a table. This works EVERY time.In the Code B part of the AutoNew procedure, the code should select the content of the cell. This works most of the time, but when it fails and generates the error, the Form1 code hasn’t finished executing yet.
How do I stop Code B from executing before Form1 Code is finished executing.
Cheers
Stephen, RedGalaxy Darwin, Australia
-
Moved by
Monday, February 18, 2013 11:14 AM
VBA & Word-specific, not using VSTO
-
Moved by
Answers
-
The solution has to re-write the code so that there aren’t possibilities for the code in the main module to execute while a form is being displayed. Essentially what I have done is taken Code Block B and incorporated it into Form 1. Also, Form
2 was being used as a notification to the user. I have substituted that with a msgbox the is part of Form 1 cmdOK_Click procedure.So, while Word was misbahaving by executing subsequent code before previous code was finished executing, it turns out my predecessor had poorly written the solution and a rewrite was required.
Stephen, RedGalaxy Darwin, Australia
-
Marked as answer by
RedGalaxy
Tuesday, February 26, 2013 1:23 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 "\\SERVERSHARE\HCD\HCD General\Templates\"
Documents.Open FileName:= _
"\\SERVERSHARE\HCD\HCD General\Templates\Heavy 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.