Проблема
При попытке использовать 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
Нужна дополнительная помощь?
Нужны дополнительные параметры?
Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.
В сообществах можно задавать вопросы и отвечать на них, отправлять отзывы и консультироваться с экспертами разных профилей.
I’m trying to create an appointment in Outlook, with Word VBA, based on the data provided in the userform loaded when the Word document containing the macro is opened.
I end up with a run time error when the macro executes the paste function.
Dim OutApp As Object
Dim OutMail As Object
Dim OutInsp As Outlook.Inspector
Dim WdApp As Word.Application
Dim OutDoc As Word.Document
Dim WdSel As Word.Selection
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(1)
If request_Form.ComboBox3.Value = "****" Then
With ActiveDocument.Bookmarks("recipient_Name")
.Range.Text = "Uwe"
End With
With ActiveDocument.Bookmarks("applicant_Name")
.Range.Text = Replace(request_Form.TextBox1.Value, "_", ", ")
End With
With OutMail
.MeetingStatus = olMeeting
.RequiredAttendees = "@live.in"
.Subject = request_Form.TextBox1.Value & " Work From Home"
.Location = "Home"
.BusyStatus = olFree
.ReminderSet = False
If request_Form.CheckBox1.Value = False Then
.Start = DateValue(request_Form.TextBox2.Value) + TimeValue(request_Form.ComboBox1.Value)
.End = DateValue(request_Form.TextBox2.Value) + TimeValue(request_Form.ComboBox2.Value)
Else
.AllDayEvent = True
End If
.Display
End With
Set OutInsp = OutMail.GetInspector
Set OutDoc = OutInsp.WordEditor
Set WdApp = OutDoc.Application
Set WdSel = WdApp.Windows(1).Selection
Documents("Home Office Request Form.docm").Range.Copy
With OutMail
WdSel.PasteAndFormat Type:=wdFormatOriginalFormatting
End With
save_file
MsgBox "A copy of this file has been stored in your desktop for your
reference.", vbOKOnly + vbInformation, "Status Information"
End Sub
The program creates an appointment based on the data filled in the userform and copies the entire content in the Word document and pastes in the body of the appointment».
When wdsel.pasteandformat
is executed it results in run time error. This error doesn’t happen often so it is hard to understand what going wrong. Lets says 70% of the time it works.
MrViper Пользователь Сообщений: 60 |
Excel 2010 Возникает ошибка 4605 — «Метод или свойства не доступны, поскольку буфер обмена пуст или содержит неверные данные» в VBA при ставки таблицы из Excel в Word такой строкой: wordApp.Selection.PasteExcelTable False, False, False, где wordapp объект Word Пробовал так — после ошибки код останавливаю, и пытаюсь через Ctrl+V вставить в Word — не выходит; такой ощущение что буфер пуст. Причем на листе Excel копируемая область показана (обведена мегающим диапазоном). НО! вставляю на любой лист Excel и чудесным образом буфер опять заполнился, но в word всталять все равно не хочет. Как быть? |
MrViper Пользователь Сообщений: 60 |
Вот небольшой примерчик |
subtlety Пользователь Сообщений: 375 |
не очень понятно, там цикл. Так работает: Private Sub w_word_go() Set wordApp = CreateObject(«word.application») ‘For i = 1 To 30 Application.ScreenUpdating = True |
subtlety Пользователь Сообщений: 375 |
*зачем там цикл, я имел в виду, конечно. |
MrViper Пользователь Сообщений: 60 |
Просто ошибка возникает не всегда на первой вставки, иногда посредине, иногда и во все не возникает |
KuklP Пользователь Сообщений: 14868 E-mail и реквизиты в профиле. |
MrViper, у меня никакой ошибки не возникает. Хоть с циклом, хоть без. Значит, ошибка не в коде. С увеличением числа форумов, куда Вы запостили вопрос, шансы получить исправленный код не увеличатся. Кривая инсталляция Офиса, загнанная система и т.д.. Я сам — дурнее всякого примера! … |
MrViper Пользователь Сообщений: 60 |
Не то чтобы получить исправленный код…скорее получить ответ, почему в 2003 офисе тот же код пашет, а в 2010 нет. У меня к Вам KukLP только 1 вопрос — Вы смотрели в 2010 офисе? |
subtlety Пользователь Сообщений: 375 |
{quote}{login=MrViper}{date=15.02.2012 12:36}{thema=Re: }{post}{quote}{login=subtlety}{date=15.02.2012 12:16}{thema=}{post}*зачем там цикл, я имел в виду, конечно.{/post}{/quote} Просто ошибка возникает не всегда на первой вставки, иногда посредине, иногда и во все не возникает{/post}{/quote} теперь понял. после строки: To KuklP. У меня тоже выскакивает эта ошибка и тоже нестабильно. |
MrViper Пользователь Сообщений: 60 |
Спасибо subtlety; Информации на заметку — на машинах с разной производительности код ведет себя по разному, где пролетает, а где выдает ошибку |
KuklP Пользователь Сообщений: 14868 E-mail и реквизиты в профиле. |
Сейчас пять раз подряд запускал в 2010 без очистки буфера, с циклом. Все работает, ошибок нет. 150 проходов без ошибок. Я сам — дурнее всякого примера! … |
MrViper Пользователь Сообщений: 60 |
Незнаю…возможно зависит от конретной машины и параметров системы. Я протестировал на другом, более мощном компьютере, без очистки буфера — тоже все нормально. Замечу, что ошибка ругается на том что буфер пуст, а не переполнен. Т.е как бы таблица в буфере есть, но для Word’a ее нет. Загадка какая-то. Но предлагаю закрыть тему, дабы не гадать на кофейной гуще. Решение subtlety показал. |
subtlety Пользователь Сообщений: 375 |
#12 15.02.2012 15:07:23 Пожалуйста. |
14 / 14 / 5 Регистрация: 24.02.2014 Сообщений: 84 |
|
1 |
|
21.03.2014, 14:47. Показов 5726. Ответов 3
Добрый день, уважаемые гуру vba.
0 |
15137 / 6411 / 1730 Регистрация: 24.09.2011 Сообщений: 9,999 |
|
21.03.2014, 15:07 |
2 |
Возможно сталкивались Сталкивался. При каких-то действиях с Selection, когда ничего не было выделено.
1 |
sernik 14 / 14 / 5 Регистрация: 24.02.2014 Сообщений: 84 |
||||
21.03.2014, 15:37 [ТС] |
3 |
|||
У меня вроди не идет selection, но в разных r.PasteSpecial выдает ошибку. Может как то очищать буфер, либо разным переменным задавать копируемые данные?
0 |
sernik 14 / 14 / 5 Регистрация: 24.02.2014 Сообщений: 84 |
||||||
21.03.2014, 17:22 [ТС] |
4 |
|||||
В общем, как решил мою проблему, возможно кому то пригодится, да и у меня будет в закладках на память.
Вложения
1 |
How to Fix Run Time Error 4605 in MS Word?
Updated on August 18, 2022
If you ever encountered the error 4605 While working on word document that is an indication of corruption on the file. All you must do is, fix the MS word corruption and repair the document. SFWare Word Document Repair is the most recommended and a convenient tool fix severe Word document issues in a jiffy, you can download for free and try.
Download Now
Runtime error 4605 is an error encountered in MS Word due to corruption in the word document or if the document that you are referencing to is not able open due to changed file property.
What is Word Document Property?
Document property is known as the metadata which contains all the details about a file. This metadata is used by the operating system to describe and identify a file. It includes details such as title, author name, subject and keywords.
Symptoms of Runtime Errors
When trying to change the properties of the document, you might encounter any of these runtime error codes and below each code are the error messages you will encounter along with it.
Run-time error 4248:
This command is not available because no document is open.
Run-time error 4605:
Trying to do changes in the properties of a document using Microsoft VBA: Run-time error ‘4605’: This method or property is not available because a document window is not active.
Due to corruption of word file: Run-time error ‘4605’: The Unprotect method or property is not available because this command is not available for reading
When you are trying to paste excel sheet table in word file: Run-time error ‘4605’: This method or property is not available because the current selection is at the end of a table row.
Run-time error 5941:
The requested member of the collection does not exist.
How to Repair Word Document showing Run Time Error 4605?
Method 1: Fix Runtime Error using Windows Repair Feature
Before heading to an automated method, try fixing the issues using an inbuilt MS Office feature. Although inbuilt tool is quick and easy, it only helps you fix minor issues on the document.
- 1. Firstly, open the MS Word >> tap on the File option >> Open
- 2. Next, go to the location where your damaged MS Word file is located.
- 3. After that, choose a Word file and tap on down arrow near the Open
- 4. Lastly, press on Open & Repair option, and then MS Word will try to repair and open document after removing its file issues.
If your document is severely corrupt, all you need is an efficient and effective MS Word document repair tool.
MS Word Repair Tool to Fix Run Time Error
Be it any runtime error you had encountered, with the help of safe and trusted MS Word repair tool, you can repair your document and fix runtime error.
SFWare Word Document Repair tool is the most trusted and recommended MS repair tool. The tool easily fixes MS word issues such Run-time error. The tool works on read only mode therefore, the original file is unchanged, the integrity of the file is unaltered. This program can easily fix DOC and DOCX files created on any versions of MS Word including the latest 2019, 2016 and the older version.
Download Now
Also, the tool helps you fix corrupt Word document on memory cards, external hard drives, hard disk, USB drives, memory sticks and other devices. Not only Runtime error, other issues such as not enough memory, macro error, repair word files after the system crash, Word 2010 not responding or not opening error, file permission error, etc.
Repair MS Word Run-Time Error 4605 using SFWare Word Document Repir Tool
Download SFWare Word Document Repair Toolkit on your Windows computer where document resides. Launch and run the utility to start with repair process.
Save this repaired file to desired destination location on system drive. With the help of the tool, you can also fix issues such as MS word not stopped working or responding.
Tips to Avoid Word Document corruption or damage
- Never try changing the properties or preferences of your Word file if you are not completely aware or without having complete knowledge
- Always keep your drive safe and secure using a powerful antivirus software to avoid risk of the malicious viruses
- Also, always make sure you keep the backup of your important files and documents.
Bottom Line:
Runtime Errors are the most common errors encountered in MS documents. With the help of the above methods mentioned, you should be able to fix the error.