The object invoked has disconnected from its clients vba excel

I know I’ve seen references to this issue before, but I have tried several of the suggestions and I am still getting the error. I have a workbook that assembles data from another book and generates a report. I then want to make a new workbook, copy the report information into the new book, save the new book and close it, and then move on to the next report. It should do this around 10 times. In the part of my code where I am copying and pasting the sheets, I am getting an error

Error -2147417848 Automation error The object invoked has
disconnected from its clients

I have checked other postings about this error, and tried the suggested solutions without any results. the interesting thing is that sometimes it will make it through 5 cycles of code before breaking, sometimes only 2. The only consistency is that it always breaks in the same place

fromBook.Sheets(«Report»).Copy Before:=newBook.Sheets(«Sheet1»)

I have option Explicit at the top of the module, and I have checked to make sure that there are not any globals inside of the sub it is breaking in. That being said, It’s entirely possible I have overlooked something. I also put a «timer» in at one point to make sure that the excel sheets were not walking over each other.

I could really use the help!

Here is my sub’s code:

Sub CreateAndSave(ByRef Reg As Integer, ByVal j As Integer)

        Dim fromBook As Workbook
        Dim fromSheet As Worksheet
        Dim newBook As Workbook
        Dim fileExists As Boolean
        Dim i As Integer
        Dim Holder As Integer


        Application.ScreenUpdating = False
        Application.DisplayAlerts = False

            Set fromBook = Application.Workbooks("Region_Audit_Report")
            Set newBook = Workbooks.Add

           With newBook
            .SaveAs Filename:="G:DataTeamExcelDevAudit ReportRegion WorkbooksRegion" & Reg & " " & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & ".xlsx" _
            , FileFormat:=xlOpenXMLWorkbook
           End With

        Set newBook = Application.Workbooks("Region" & Reg & " " & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & ".xlsx")

        fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")
        fromBook.Sheets("MonthData").Copy After:=newBook.Sheets("Report")

        newBook.Sheets("MonthData").Range("A1") = "Month"
        newBook.Sheets("MonthData").Range("B1") = "Store#"
        newBook.Sheets("MonthData").Range("C1") = "District"
        newBook.Sheets("MonthData").Range("D1") = "Region"
        newBook.Sheets("MonthData").Range("E1") = "Due Date"
        newBook.Sheets("MonthData").Range("F1") = "Comp Date"
        newBook.Sheets("MonthData").Range("G1") = "# of Errors"
        newBook.Sheets("MonthData").Range("H1") = "Late?"
        newBook.Sheets("MonthData").Range("I1") = "Complete?"

        newBook.Sheets("MonthData").Range("A1:I1").Interior.ColorIndex = 43


            newBook.Save

            newBook.Close


            Application.DisplayAlerts = True

    End Sub

RRS feed

  • Remove From My Forums
  • Question

  • I got this error: «Automation error: The object invoked has disconnected from its clients» when I try to save a document(Word), spredsheet(Excel) etc. in Office 2010.

    I try it for office 2007 /2003, the issue is same.

    It is a new error, my Office have worked fine with this installation before.

All replies

  • Hi,

    Can you check if the Security Update MS12-060 has been installed ?
    If so, please try the following on a test machine.

    Open Notepad and paste the content below the line.
    Save the File as .bat and run it. Try again Word to see if you get the message.

    ===============================================

    reg delete hkcrtypelib{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}2.0 /f

    if exist %systemroot%SysWOW64cscript.exe goto 64 
    %systemroot%system32regsvr32 /u mscomctl.ocx
    %systemroot%system32regsvr32 mscomctl.ocx
    exit

    :64 
    %systemroot%sysWOW64regsvr32 /u mscomctl.ocx
    %systemroot%sysWOW64regsvr32 mscomctl.ocx
    exit

    ===============================================

    Take a look also at this one: http://blogs.technet.com/b/the_microsoft_excel_support_team_blog/archive/2012/08/15/quot-unspecified-automation-error-quot-after-applying-ms12-060.aspx

    Cheers, Petru

  • Appreciate your quick reply.

    I have try to run your .bat file, but occurred this error message, means «Mscomctl.ocx has been loaded successfully but failed to call DllRegisterServer, the error code is 0x80004005.»

    • Edited by

      Monday, August 27, 2012 3:31 AM

  • @Logoncafe, please try to then run the script again with Administrator permission, hold Shift key and right click on it, and choose Run as administrator.


    Max Meng
    TechNet Community Support

    • Edited by
      Max Meng
      Wednesday, August 29, 2012 4:25 AM

  • Hi Max Meng,

    I execute the about scripts successfully, but the automation error still exists. -_-!

  • ehmmm…

    Try to run Word in safe mode, and save the document again.

    If this error won’t occur in the safe mode, remove the macros or disable the add-ins and check again.


    Max Meng

    TechNet Community Support

  • Any updates/ fresh insights on this? 

    I get the exact same error when trying to use «Save as» from Excel.  I get it regardless of the state of the document, whether I try to save an empty document from a freshly opened Excel session or if I try to «Save as» an existing document. Just using
    Save on an existing document does not initiate the error.

    In Word I get the message only sporadically when trying to save.

    I have tried the registry fix to no avail and running in safe mode does not make any difference. 

    I tried reinstalling Microsoft Office (2007) — that did not help. Today IT department rolled out Office 2010 and I installed that, but I still get the same error.

    As for the OP my problems started recently, and without remembering the exact date it was definitely later than the  15th of August (time of the infamous patch).

    We are a pretty big organisation, and as far as I know none of my colleagues have the same problem and our IT helpdesk is miffed.

    The only solution left to me now is to reinstall windows unless some clever soul in here have a tip that might remedy the issue.

    • Edited by
      olecs
      Monday, September 10, 2012 12:42 PM

  • I, too, was still having the error message in Excel 2010 on one user’s computer.  I even tried creating a clean Excel14.xlb file, but that didn’t make a difference.

    At this point I knew it was likely to be an add-in creating the issue since I was getting this error message just opening Excel without actually opening an existing file.

    I went to File>Options>Add-Ins>Excel Add-Ins and unchecked «Analysis Toolpak — VBA», closed Excel, opened Excel and the message had gone away.

    Then I enabled the Add-In again, but the error message did not return.  So far, so good, but time will tell if this was the fix. 

    What actually happened under the hood, though? 


    Views expressed do not represent those of my employer.

 

vukula

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

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

#1

23.11.2015 12:09:26

Excel 2010
Имеет место рандомная ошибка. Т.е. иногда возникает, иногда — нет.
«Run-time error ‘-2147417848 (80010108)’
Automation error. The object invoked has disconnected from its clients»

Если возникает, то дальнейший дебаг и запуск дает
«Run-time error ‘1004’: Метод Insert класса Range завершен неверно»

Помогите пжл. В каком направлении искать. Спасибо.

Код
Sub addOp()
    Dim Name As String
           
    Name = Cells(5, 2)
    Size = Cells(2, 2).Value
    Avr = Cells(6, 2).Value
    Eop = Cells(7, 2).Value
              
    Sheets("tmpl").Copy Before:=Sheets(13)
    Sheets("tmpl (2)").Name = Name
    
    Sheets(Name).Visible = True
    Sheets(Name).Select
    Cells(3, 2) = Name
    Cells(2, 1) = Size
    Cells(1, 2) = Avr
    Cells(2, 2) = Eop
       
'вставка в рублевый лист
    Sheets("tmplFrur").Visible = True
    Sheets("tmplFrur").Select
    Range("B1:B147").Select
    Selection.Copy
    Sheets("resumeRur").Select
    Range("C1").Select
    Selection.Insert Shift:=xlToRight    'вот на этой строке вылетает ошибка. А иногда не вылетает.
    Cells(1, 3) = Avr
    Cells(2, 3) = Eop
    Cells(3, 3) = Name
    Columns("c:m").ColumnWidth = 12.5
  
    
    Sheets("tmplFrur").Visible = False
    Sheets("tmplFcur").Visible = False
    Sheets(Name).Select
    Range("b4").Select
    Application.CutCopyMode = False
End Sub
 

CAHO

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

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

А она возникает скорее всего, потому что макрос у Вас из модуля выполняется и обращается к конкретным ячейкам листам и диапазонам через Select.
Уберите все селекты и лишние переменные, которые в начале даже не описаны. Пропишите нормальные пути к листам и ячейкам. У вас скорее всего не на те листы или имена попадает при выполнении макроса. А вообще пример бы.

Мастерство программиста не в том, чтобы писать программы, работающие без ошибок.
А в том, чтобы писать программы, работающие при любом количестве ошибок.

 

vukula

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

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

#3

23.11.2015 12:43:54

Цитата
CAHO написал: Пропишите нормальные пути к листам и ячейкам

Что Вы подразумеваете под «нормальными путями»?
Пример, в смысле «файл»?

 

justirus

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

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

#4

23.11.2015 12:49:46

Цитата
vukula написал: нормальные пути к листам и ячейкам

Ну например:
Name = Cells(5, 2)
можно заменить на:
Name = ThisWorkbook.Worksheets(«Параметры»).Cells(5, 2)
разница в том, что в зависимости от того какой лист или книга буду активны в момент запуска макроса, переменная name будет иметь разные значения, в моем варианте всегда одно значение.

Изменено: justirus03.12.2015 01:06:25

 

CAHO

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

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

#5

23.11.2015 12:57:10

Например что-то вроде такого

Код
Sub addOp()
    Name = Cells(5, 2)
    Sheets("tmpl").Copy Before:=Sheets(13)
    Sheets("tmpl (2)").Name = Cells(5, 2)
    Sheets(Name).Cells(3, 2) = Name
    Sheets(Name).Cells(2, 1) = Cells(2, 2).Value
    Sheets(Name).Cells(1, 2) = Cells(6, 2).Value
    Sheets(Name).Cells(2, 2) = Cells(7, 2).Value
    Sheets("tmplFrur").Range("B1:B147").Copy
    Sheets("resumeRur").Range("C1").Insert Shift:=xlToRight
    Sheets("resumeRur").Cells(1, 3) = Cells(6, 2).Value
    Sheets("resumeRur").Cells(2, 3) = Cells(7, 2).Value
    Sheets("resumeRur").Cells(3, 3) = Name
    Sheets("resumeRur").Columns("c:m").ColumnWidth = 12.5
    Sheets(Name).Range("b4").Select
    Application.CutCopyMode = False
End Sub

Мастерство программиста не в том, чтобы писать программы, работающие без ошибок.
А в том, чтобы писать программы, работающие при любом количестве ошибок.

 

vukula

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

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

Спасибо за участие.
Минимизировал селекты, НО ошибка все равно вылетает.
Выявил следующую зависимость.
Файл сохраняется как шаблон эксель с поддержкой макросов.
Изначально Name забито как «2013» (т.е. год).
Если я открываю файл и запускаю макрос, не меняя Name, ошибка не вылетает.
Если открываю файл и ввожу первый отчетный период, отличный от сохраненного в шаблоне, например, 2014й, ошибка вылетает.
Файл вкладываю.

Изменено: vukula23.11.2015 17:20:59

 

vukula

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

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

вот что говорит микрософт

правда мне это не помогло

Изменено: vukula24.11.2015 09:09:47

 

hyperion3330

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

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

#8

13.07.2021 18:32:31

Недавно тоже столкнулся с такой проблемой..
Как оказалось — из-за того что пытался менять значения ячеек на скрытом листе..
Как только перенёс строку «Sheets(Name).Range(«b4″).Visible = True»
Перед изменением значений, сразу всё стало нормально работать :)
Вдруг кому-то пригодится…

  • Remove From My Forums
  • Question

  • Good day all,

    I just read lots of articles bout this error but could not handle how to solve it. the latest article was «INFO: Error or Unexpected Behavior with Office Automation When You Use Early Binding in Visual Basic» so I considered i need to do qualifying
    my code but i do not know how?!

    here is the codes which I wrote on a excel vba userform:

    Private Sub CommandButton1_Click()
    Application.Calculation = False
    Worksheets("Data Base").Activate
    
        MSG1 = MsgBox("Do you want to submit the form?", vbYesNo)
        If MSG1 = vbYes Then
            Dim ssheet As Worksheet
            
            Set ssheet = ThisWorkbook.Sheets("Data Base")
    
            nr = ssheet.Cells(Rows.Count, 2).End(xlUp).Row + 1
    
                ssheet.Cells(nr, 2) = Me.TextStockNo
                ssheet.Cells(nr, 3) = Me.ComboRepName
                ssheet.Cells(nr, 5) = Me.DTPickerDate
                ssheet.Cells(nr, 6) = Me.TextYearModel
                ssheet.Cells(nr, 7) = Me.ComboVehicleMake
                ssheet.Cells(nr, 8) = Me.TextDescription
                ssheet.Cells(nr, 9) = Me.TextRegNo
                ssheet.Cells(nr, 9) = Me.TextMileage
                ssheet.Cells(nr, 11) = Me.ComboColour
                ssheet.Cells(nr, 12) = Me.TextBought
                ssheet.Cells(nr, 13) = Me.TextSold
                ssheet.Cells(nr, 15) = Me.ComboDealer
                ssheet.Cells(nr, 16) = Me.ComboAdvert
                ssheet.Cells(nr, 17) = Me.TextAddComments
                ssheet.Cells(nr, 18) = Me.DTPickerInvoiceDate
                ssheet.Cells(nr, 19) = Me.TextInvoiceNo
                
                
            MSG2 = MsgBox("Do you want to input new field?", vbYesNo)
            If MSG2 = vbYes Then
            Unload Me
            Worksheets("Data Base").Activate
            userform1.Hide
            userform1.Show
            Else
            Unload Me
            End If
    
    
        Else
           Unload Me
           Worksheets("Data Base").Activate
           userform1.Hide
           userform1.Show
         End If
    
     Application.Calculation = True
    End Sub
    
    
    
    Private Sub CommandButton2_Click()
     Unload Me
    End Sub
    
    Private Sub CommandButton3_Click()
    Unload Me
    Worksheets("Data Base").Activate
    userform1.Hide
    userform1.Show
    End Sub
    
    Sub Open_Form()
        Worksheets("Data Base").Activate
       
        userform1.Show
        
        
    End Sub

    It is a data entry form which gives the user options to reset the form, submit or reload it. I it works fine at same time but as long as I submit for first time and reload it to submit next item it gives me that error.

    I checked it on another pc and it works fine, I am not sure what is wrong with my pc.

    • Moved by

      Monday, December 16, 2013 8:51 AM
      (from vb) more related

Answers

  • Hello SJafary,

    For example, the
    INFO: Error or Unexpected Behavior with Office Automation When You Use Early Binding in Visual Basic article provides the following sample:

    MsgBox "Number of workbooks: " & Workbooks.Count, vbMsgBoxSetForeground

    where the Workbooks object is a shortcut to the Application.Workbooks property. To resolve problems, you must fully qualify the Workbooks object that you reference for the count, as follows:

    MsgBox "Number of workbooks: " & oXL.Workbooks.Count, vbMsgBoxSetForeground

    Now the Workbooks property is specified explicitly. The article suggests avoiding shortcuts and use properties and methods that comes from the Application class (not global properties).

    • Edited by
      Eugene Astafiev
      Monday, December 16, 2013 9:30 AM
    • Marked as answer by
      Marvin_Guo
      Wednesday, December 25, 2013 9:41 AM

I know I’ve seen references to this issue before, but I have tried several of the suggestions and I am still getting the error. I have a workbook that assembles data from another book and generates a report. I then want to make a new workbook, copy the report information into the new book, save the new book and close it, and then move on to the next report. It should do this around 10 times. In the part of my code where I am copying and pasting the sheets, I am getting an error

Error -2147417848 Automation error The object invoked has
disconnected from its clients

I have checked other postings about this error, and tried the suggested solutions without any results. the interesting thing is that sometimes it will make it through 5 cycles of code before breaking, sometimes only 2. The only consistency is that it always breaks in the same place

fromBook.Sheets(«Report»).Copy Before:=newBook.Sheets(«Sheet1»)

I have option Explicit at the top of the module, and I have checked to make sure that there are not any globals inside of the sub it is breaking in. That being said, It’s entirely possible I have overlooked something. I also put a «timer» in at one point to make sure that the excel sheets were not walking over each other.

I could really use the help!

Here is my sub’s code:

Sub CreateAndSave(ByRef Reg As Integer, ByVal j As Integer)

        Dim fromBook As Workbook
        Dim fromSheet As Worksheet
        Dim newBook As Workbook
        Dim fileExists As Boolean
        Dim i As Integer
        Dim Holder As Integer


        Application.ScreenUpdating = False
        Application.DisplayAlerts = False

            Set fromBook = Application.Workbooks("Region_Audit_Report")
            Set newBook = Workbooks.Add

           With newBook
            .SaveAs Filename:="G:DataTeamExcelDevAudit ReportRegion WorkbooksRegion" & Reg & " " & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & ".xlsx" _
            , FileFormat:=xlOpenXMLWorkbook
           End With

        Set newBook = Application.Workbooks("Region" & Reg & " " & Month(Date) & "-" & Day(Date) & "-" & Year(Date) & ".xlsx")

        fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")
        fromBook.Sheets("MonthData").Copy After:=newBook.Sheets("Report")

        newBook.Sheets("MonthData").Range("A1") = "Month"
        newBook.Sheets("MonthData").Range("B1") = "Store#"
        newBook.Sheets("MonthData").Range("C1") = "District"
        newBook.Sheets("MonthData").Range("D1") = "Region"
        newBook.Sheets("MonthData").Range("E1") = "Due Date"
        newBook.Sheets("MonthData").Range("F1") = "Comp Date"
        newBook.Sheets("MonthData").Range("G1") = "# of Errors"
        newBook.Sheets("MonthData").Range("H1") = "Late?"
        newBook.Sheets("MonthData").Range("I1") = "Complete?"

        newBook.Sheets("MonthData").Range("A1:I1").Interior.ColorIndex = 43


            newBook.Save

            newBook.Close


            Application.DisplayAlerts = True

    End Sub

Like this post? Please share to your friends:
  • The number word song
  • The noun of the word exist is
  • The noun of the word describe
  • The noun of the word confused
  • The noun of the word care