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.
Проблема
При попытке использовать 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
Нужна дополнительная помощь?
Нужны дополнительные параметры?
Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.
В сообществах можно задавать вопросы и отвечать на них, отправлять отзывы и консультироваться с экспертами разных профилей.
here is a function to detect if Word is running and another one to detect if a specific document is open:
Friend Function WordIsOpen() As Boolean
Dim WindowName As String
Dim FlagWordIsOpen As Boolean
Dim p() As Process
p = Process.GetProcessesByName("WinWord")
If p.Count > 0 Then
FlagWordIsOpen = True
Else
FlagWordIsOpen = False
End If
Return FlagWordIsOpen
End Function
Here is the function to detect if a document is already open:
Friend Function DocumentIsOpen(Documento As String) As Boolean
Dim WindowName As String
Dim FlagOpenDocument As Boolean
Dim FileName As String
Dim PathName As String
If My.Computer.FileSystem.FileExists(Documento) Then
FileName = My.Computer.FileSystem.GetName(Documento)
Else
FileName = Documento
End If
Dim lhWndP As Long
Dim Flag As Boolean
Flag = False
Try
If GetHandleFromPartialCaption(lhWndP, Replace(FileName, System.IO.Path.GetExtension(FileName), "", VB.CompareMethod.Text)) = True Then
Flag = True
End If
Catch
End Try
Return Flag
End Function
Here is the function GetHandleFromPartialCaption:
Friend Function GetHandleFromPartialCaption(ByRef lWnd As Long, ByVal sCaption As String) As Boolean
Dim sStr As String
Dim strBuilder As New System.Text.StringBuilder(256)
Dim lhWndP As Long
Dim Flag As Boolean
System.Windows.Forms.Application.DoEvents()
Flag = False
lhWndP = FindWindow(vbNullString, vbNullString) 'PARENT WINDOW
Do While lhWndP <> 0
Try
sStr = GetText(CType(lhWndP, IntPtr))
If InStr(sStr.ToUpper(), sCaption.ToUpper(), VB.CompareMethod.Text) > 0 Then
Flag = True
lWnd = lhWndP
Exit Do
End If
Catch
End Try
lhWndP = GetWindow(CType(lhWndP, IntPtr), GW_HWNDNEXT)
Loop
Return Flag
End Function
Here is the declaration for the API FindWindow:
Friend Declare Function FindWindow Lib "User32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Here is the function GetText:
Friend Function GetText(ByVal hWnd As IntPtr) As String
Dim length As Integer
If hWnd.ToInt32 = 0 Then
Return Nothing
End If
length = GetWindowTextLength(hWnd)
If length = 0 Then
Return Nothing
End If
Dim sb As New System.Text.StringBuilder("", length)
GetWindowText(CInt(hWnd), sb, sb.Capacity + 1)
Return sb.ToString()
End Function
Here is the declaration for GetWindowTextLength:
<DllImport("user32.dll")> Friend Function GetWindowTextLength(ByVal hwnd As IntPtr) As Integer
End Function
Here is the declaration for GetWindowText:
<DllImport("user32.dll", EntryPoint:="GetWindowText")>
Friend Function GetWindowText(ByVal hwnd As Integer, ByVal lpString As System.Text.StringBuilder, ByVal cch As Integer) As Integer
End Function
Here is the declaration for GetWindow:
<DllImport("user32.dll")> Friend Function GetWindow(ByVal hWnd As IntPtr, uCmd As UInteger) As Long
End Function
… A bit complicated, but I hope it helps!
- Remove From My Forums
-
Question
-
Hello everybody,
at a customer’s site there are Word macros running since _decades_ just fine. One thing they do is copy the whole current document’s Range (into the Windows clipboard), create a new document, and Paste in the new document’s Range.
Since a few weeks, the customer uses Office 365 (32 bit), and code like this fails:
sourceRange.Copy() destinationRange.Paste()
VBA stops with error 4605 on the Paste() call. We could somewhat help by inserting a DoEvents() between Copy() and Paste(). But this does not help always.
What did change in Word’s handling of the clipboard so that something copied just one statement before cannot be pasted?
Best Regards, Stefan Falk
-
Moved by
Thursday, July 18, 2019 2:59 AM
-
Moved by
Answers
-
Hello everybody!
The problem is found and there is a workaround: Turn off clipboard history («Zwischenablage-Verlauf» in German)!
The following little test macro runs just fine without clipboard history, but fails after just a few copy/paste iterations if clipboard history is turned on:
Option Explicit Public Sub TestClipboard() Dim source As Document, target As Document, _ text As String, _ i As Integer For i = 1 To 1000 text = text & "Dies ist ein Test. " Next Set source = Documents.Add source.Range.Text = text Set target = Documents.Add For i = 1 To 100 Debug.Print i source.Range.Copy DoEvents target.Range.Paste DoEvents Next target.Close False source.Close False Debug.Print "Finished" End Sub
So clipboard history seems to have at least one little problem.
Best Regards, Stefan Falk
-
Marked as answer by
Stefan Falk
Wednesday, April 1, 2020 10:22 AM
-
Marked as answer by
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 Пожалуйста. |