Vba word run time error 4605

Explains how some run-time error messages may occur when you change the properties of a document by using VBA in Word 2003 or Word 2007. You may experience the errors when you the document is unopened.

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 Sub

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

End 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 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

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?

Проблема

При попытке использовать 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

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

14 / 14 / 5

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

Сообщений: 84

1

21.03.2014, 14:47. Показов 5378. Ответов 3


Добрый день, уважаемые гуру vba.
Надеюсь снова на вашу помощь. Настроил файл для переноса из Excel в Word данных, таблиц, картинок. Но теперь возникает ошибка «Run-time erroe ‘4605’: в разных местах кода при вставке таблицы из Excel в Word PasteSpecial . Не знаю, как от неё избавиться.
Возможно сталкивались с подобной проблемой и сможете мне помочь. Файлы в приложении.
Оба файла разархивировать необходимо и указать путь в шаблону .dot в excel файле.

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



0



15131 / 6405 / 1730

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

Сообщений: 9,999

21.03.2014, 15:07

2

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

Возможно сталкивались

Сталкивался. При каких-то действиях с Selection, когда ничего не было выделено.
От Selection вообще надо избавляться. А качать 7 метров не хочется.



1



sernik

14 / 14 / 5

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

Сообщений: 84

21.03.2014, 15:37

 [ТС]

3

У меня вроди не идет selection, но в разных r.PasteSpecial выдает ошибку. Может как то очищать буфер, либо разным переменным задавать копируемые данные?
Пример куска кода, идут однотипные строки, с одной и той же целью скопировать и вставить данные. Может быть подскажите, что можно сделать с ними, что бы избижать/обойти данную ошибку?

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 Set r = .Bookmarks.Item("Износ").Range
         N = r.Start
         If r.Tables.Count Then r.Tables(1).Delete
       Sheets("Износ").Range("A7:C11").Copy
        r.PasteSpecial
        r.Start = N
        .Bookmarks.Add "Износ", r
 
   Set r = .Bookmarks.Item("Отделка").Range
         N = r.Start
         If r.Tables.Count Then r.Tables(1).Delete
    Sheets("Отделка").Range("A1:H8").Copy
        r.PasteSpecial
        r.Start = N
        .Bookmarks.Add "Отделка", r
    
   Set r = .Bookmarks.Item("Описание_АН").Range
         N = r.Start
         If r.Tables.Count Then r.Tables(1).Delete
     Sheets("Описание АН").Range("A1:E17").Copy
        r.PasteSpecial
        r.Start = N
        .Bookmarks.Add "Описание_АН", r
    
   Set r = .Bookmarks.Item("СП").Range
         N = r.Start
         If r.Tables.Count Then r.Tables(1).Delete
     Sheets("СП").Range("A1:J26").Copy
        r.PasteSpecial
        r.Start = N
        .Bookmarks.Add "СП", r



0



sernik

14 / 14 / 5

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

Сообщений: 84

21.03.2014, 17:22

 [ТС]

4

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

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Public Sub relaseBookmark(bookmarkName, sheetName, ranges As String)
Call clearClipboard
        
On Error GoTo ErrorHandler
 
With app.ActiveDocument
   Set r = .Bookmarks.Item(bookmarkName).Range
         N = r.Start
         If r.Tables.Count Then r.Tables(1).Delete
        Sheets(sheetName).Range(ranges).Copy
 
        r.PasteSpecial
        r.Start = N
        .Bookmarks.Add bookmarkName, r
End With
Exit Sub
 
ErrorHandler:
Call clearClipboard
Call relaseBookmark(bookmarkName, sheetName, ranges)
 
End Sub
 
Public Sub clearClipboard()
        OpenClipboard 0&
        EmptyClipboard
        CloseClipboard
End Sub

Вложения

Тип файла: rar 21.03.2014.rar (7.42 Мб, 20 просмотров)



1



Содержание

  1. You receive run-time error 4248, 4605 or 5941 when you try to change properties on an unopened document in Word
  2. Symptoms
  3. Cause
  4. Workaround
  5. References
  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. При попытке использовать VBA для изменения свойств документа появляется сообщение об ошибке при выполнении 4248, 4605 или 5941
  12. Проблема
  13. Причина
  14. Временное решение
  15. Ссылки
  16. Microsoft visual basic runtime error 4605
  17. Asked by:
  18. Question
  19. All replies
  20. Microsoft visual basic runtime error 4605
  21. Asked by:
  22. Question
  23. All replies

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

Источник

При попытке использовать 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

Источник

Microsoft visual basic runtime error 4605

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

I wrote a script to add TAGs as comments of word document. The criteria of adding tag is based on outline numbering as document do not follow word styles, I had to use outline numbering for this purpose.

There are couple of issues I am facing.

1.) script is very slow and sometimes my word application crashes.

2.) sometimes I get a runtime error 4605 ‘This command is not available’ for line «Selection.Comments.Add Range:=Para.Range, text:=»[» & sIdLabel & sCurrentNumber & «]» & vbCrLf ‘ ID‘>»

Here is my updated code

Since you were not able to reproduce the error every time, I suspect this issue maybe relative to the context of document you were handling.

I am also trying to reproduce this issue in Word 2013 however failed. The code works well for me like figure below:

>>2.) sometimes I get a runtime error 4605 ‘This command is not available’ for line «Selection.Comments.Add Range:=Para.Range, text:=»[» & sIdLabel & sCurrentNumber & «]» & vbCrLf ‘ ID‘>»

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.

Источник

Microsoft visual basic runtime error 4605

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Asked by:

Question

I wrote a script to add TAGs as comments of word document. The criteria of adding tag is based on outline numbering as document do not follow word styles, I had to use outline numbering for this purpose.

There are couple of issues I am facing.

1.) script is very slow and sometimes my word application crashes.

2.) sometimes I get a runtime error 4605 ‘This command is not available’ for line «Selection.Comments.Add Range:=Para.Range, text:=»[» & sIdLabel & sCurrentNumber & «]» & vbCrLf ‘ ID‘>»

Here is my updated code

Since you were not able to reproduce the error every time, I suspect this issue maybe relative to the context of document you were handling.

I am also trying to reproduce this issue in Word 2013 however failed. The code works well for me like figure below:

>>2.) sometimes I get a runtime error 4605 ‘This command is not available’ for line «Selection.Comments.Add Range:=Para.Range, text:=»[» & sIdLabel & sCurrentNumber & «]» & vbCrLf ‘ ID‘>»

We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.

Источник

  • Remove From My Forums
  • Вопрос

  • 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

    • Перемещено

      18 июля 2019 г. 2:59

Ответы

  • 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

    • Помечено в качестве ответа
      Stefan Falk
      1 апреля 2020 г. 10:22

Default


Aside from the fact the code in post #7 doesn’t use .PasteAppendTable, your code works OK for me. Your code is very inefficient (e.g. nothing need ever be selected) and cluttered, though. For example, all of:

Code:

    If ActiveWindow.View.SplitSpecial = wdPaneNone Then
                ActiveWindow.ActivePane.View.Type = wdPageView
            Else
                ActiveWindow.View.Type = wdPageView
            End If
            
            ActiveDocument.Save
            
            Selection.HomeKey Unit:=wdStory
            Application.ScreenUpdating = True
            If ActiveWindow.View.SplitSpecial <> wdPaneNone Then
                ActiveWindow.Panes(2).Close
            End If
            If ActiveWindow.ActivePane.View.Type = wdNormalView Or ActiveWindow. _
                ActivePane.View.Type = wdOutlineView Then
                ActiveWindow.ActivePane.View.Type = wdPrintView
            End If
            ActiveWindow.ActivePane.View.SeekView = wdSeekCurrentPageHeader
            ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument
'            Selection.WholeStory
'    Selection.Font.Name = "Tahoma"
'    Selection.Font.Size = 10
    ActiveWindow.ActivePane.VerticalPercentScrolled = 0
    ActiveDocument.Save
     ActiveDocument.SaveAs FileName:=UsPath + "OffSwrm.doc", FileFormat:= _
            wdFormatDocument, LockComments:=False, Password:="", AddToRecentFiles:= _
            True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:= _
            False, SaveNativePictureFormat:=False, SaveFormsData:=False, _
            SaveAsAOCELetter:=False
        ActiveDocument.ExportAsFixedFormat OutputFileName:= _
        UsPath + "OffSwrm.pdf", ExportFormat:=wdExportFormatPDF, _
        OpenAfterExport:=False, OptimizeFor:=wdExportOptimizeForPrint, Range:= _
        wdExportAllDocument, From:=1, To:=1, Item:=wdExportDocumentContent, _
        IncludeDocProps:=True, KeepIRM:=True, CreateBookmarks:= _
        wdExportCreateNoBookmarks, DocStructureTags:=True, BitmapMissingFonts:= _
        True, UseISO19005_1:=False

could be reduced to:

Code:

ActiveDocument.SaveAs2 FileName:=UsPath + "OffSwrm.doc", FileFormat:=wdFormatDocument, AddToRecentFiles:=False
ActiveDocument.SaveAs2 FileName:=UsPath + "OffSwrm.pdf", FileFormat:=wdFormatPDF, AddToRecentFiles:=False

Likewise, you can do away with:

Code:

 If ActiveWindow.View.SplitSpecial = wdPaneNone Then
'        ActiveWindow.ActivePane.View.Type = wdNormalView
    Else
'        ActiveWindow.View.Type = wdNormalView
    End If

You should also declare all your variables — and only define those you actually use.

__________________
Cheers,
Paul Edstein
[Fmr MS MVP — Word]

Reply With Quote

 

MrViper

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

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

Excel 2010  

  Возникает ошибка 4605 — «Метод или свойства не доступны, поскольку буфер обмена пуст или содержит неверные данные» в VBA при ставки таблицы из Excel в Word такой строкой:  

  wordApp.Selection.PasteExcelTable False, False, False, где wordapp объект Word  

   Пробовал так — после ошибки код останавливаю, и пытаюсь через Ctrl+V вставить в Word — не выходит; такой ощущение что буфер пуст. Причем на листе Excel копируемая область показана (обведена мегающим диапазоном). НО! вставляю на любой лист Excel и чудесным образом буфер опять заполнился, но в word всталять все равно не хочет. Как быть?

 

MrViper

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

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

Вот небольшой примерчик  
Повторясь  — Excel 2010

 

subtlety

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

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

не очень понятно, там цикл.  

  Так работает:  

  Private Sub w_word_go()  

  Set wordApp = CreateObject(«word.application»)  
   wordApp.Visible = False   ‘False  
   wordApp.Documents.Add NewTemplate:=False, DocumentType:=0  
   Application.ScreenUpdating = False  

         ‘For i = 1 To 30  
       Range(Cells(1, 1), Cells(5, 10)).Copy  
       wordApp.Selection.PasteExcelTable False, False, False  
       wordApp.Selection.TypeParagraph  
   ‘Next i  

         Application.ScreenUpdating = True  
   wordApp.Visible = True  
End Sub

 

subtlety

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

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

*зачем там цикл, я  имел в виду, конечно.

 

MrViper

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

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

Просто ошибка возникает не всегда на первой вставки, иногда посредине, иногда и во все не возникает

 

KuklP

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

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

E-mail и реквизиты в профиле.

MrViper, у меня никакой ошибки не возникает. Хоть с циклом, хоть без. Значит, ошибка не в коде. С увеличением числа форумов, куда Вы запостили вопрос, шансы получить исправленный код не увеличатся. Кривая инсталляция Офиса, загнанная система и т.д..

Я сам — дурнее всякого примера! …

 

MrViper

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

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

Не то чтобы получить исправленный код…скорее получить ответ, почему в 2003 офисе тот же код пашет, а в 2010 нет. У меня к Вам KukLP только 1 вопрос — Вы смотрели в 2010 офисе?

 

subtlety

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

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

{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}  

  теперь понял.  

  после строки:  
wordApp.Selection.PasteExcelTable False, False, False  
добавьте очистку буфера.  
       Application.CutCopyMode = False  

  To KuklP. У меня тоже выскакивает эта ошибка и тоже нестабильно.  
собственно, по запросу «PasteExcelTable error 4605»  
google выдает много тредов.

 

MrViper

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

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

Спасибо subtlety;    

  Информации на заметку — на машинах с разной производительности код ведет себя по разному, где пролетает, а где выдает ошибку

 

KuklP

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

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

E-mail и реквизиты в профиле.

Сейчас пять раз подряд запускал в 2010 без очистки буфера, с циклом. Все работает, ошибок нет. 150 проходов без ошибок.

Я сам — дурнее всякого примера! …

 

MrViper

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

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

Незнаю…возможно зависит от конретной машины и параметров системы. Я протестировал на другом, более мощном компьютере, без очистки буфера — тоже все нормально. Замечу, что ошибка ругается на том что буфер пуст, а не переполнен. Т.е как бы таблица в буфере есть, но для Word’a ее нет. Загадка какая-то.  

  Но предлагаю закрыть тему, дабы не гадать на кофейной гуще. Решение subtlety показал.

 

subtlety

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

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

#12

15.02.2012 15:07:23

Пожалуйста.  
Думаю, никакой загадки нет. Какая-то тонкость работы с буфером.  
Можно пошерстить англоязычные ресурсы.

Problem

Attempts to export the document from Microsoft Word to IBM DOORS result in the Visual Basic error:

«Run-time error 4605.

This method or property is not available because the Clipboard is empty or not valid.»

Symptom

«Run-time error ‘4605’»

Cause

The Word

.docx

document contains a picture OLE object whose format is not compatible in DOORS.

Environment

Microsoft word 2013
DOORS 9.6.0.0 and later on windows

Diagnosing The Problem

Identify how the document was created. Ensure the picture OLE object was inserted by using the picture option. If the picture was copied from another Word document, the format would carry over.

Resolving The Problem

  1. Save the Word .docx file in the .doc format
  2. Export the document to DOORS

If this does not resolve the problem, you have to re-insert the picture into the document by using Insert > Pictures option in Word.

[{«Product»:{«code»:»SSKR2T»,»label»:»IBM Engineering Requirements Management DOORS»},»Business Unit»:{«code»:»BU059″,»label»:»IBM Software w/o TPS»},»Component»:»Documentation»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»9.3;9.3.0.1;9.3.0.2;9.3.0.3;9.3.0.4;9.3.0.5;9.3.0.6;9.3.0.7;9.3.0.8;9.4;9.4.0.1;9.4.0.2;9.5;9.5.0.1;9.5.0.2;9.5.1;9.5.1.1;9.5.1.2;9.5.1.3;9.5.2;9.5.2.1;9.5.2.2;9.6;9.6.0.1;9.6.1″,»Edition»:»»,»Line of Business»:{«code»:»LOB59″,»label»:»Sustainability Software»}}]

Понравилась статья? Поделить с друзьями:
  • Vba ошибка 429
  • Vba ошибка 424 object required как исправить
  • Vba отключить сообщения об ошибках
  • Vba отключить on error resume next
  • Vba unspecified error