Run time error 2147417848 80010108 vba excel

Студворк — интернет-сервис помощи студентам

Добрый день.

Долгое время работал с макросом в Эксель 2010, ищущем дубли на листе:
1. в пустую ячейку столбца С, следующую за последней заполненной, вставляется слово, по которому идёт поиск дублей (или несколько слов вставляются последовательно в соответствующее кол-во ячеек столбца С, если нужно найти дубли сразу нескольких слов);
2. выделяется ячейка, содержащая это слово (или верхнее из слов, если их несколько), запускается макрос поиска дублей по всем ячейкам столбца С;
3. макрос пробегает все ячейки столбца С и находит дубли;
4. вырезает строку/строки с ячейками от A до Z, где в столбце С был найден дубль поискового слова/слов;
5. вставляет найденные строки в пустые строки в конце файла (т.е. в строки, следующие за строками, содержащими слова, по которым ведётся поиск дублей);

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
Sub FindDub()
Range("Y:Y").Clear
Application.ScreenUpdating = False
StartCell = ActiveCell.Row
lastcell = Cells(Rows.Count, 3).End(xlUp).Row
Delta = 1
ColDub = 25
For a = 1 To StartCell - 1
  If Cells(a, 3).Value <> "" And Cells(a, ColDub).Value <> 1 Then
    For b = StartCell To lastcell
      If b <> a Then
         If UCase(Cells(a, 3).Value) = UCase(Cells(b, 3).Value) Then
          Range("A" & a & ":" & "Z" & a).Select
          Selection.Cut
          Range("A" & (lastcell + Delta) & ":" & "Z" & (lastcell + Delta)).Select
          ActiveSheet.Paste
          Delta = Delta + 1
          Cells(b, ColDub).Value = 1
         End If
      End If
    Next
  End If
  Next
    LastRow = ActiveSheet.UsedRange.Row - 1 + ActiveSheet.UsedRange.Rows.Count
    For r = LastRow To 1 Step -1
    If Application.CountA(Rows(r)) = 0 Then Rows(r).Delete
    Next r
Application.ScreenUpdating = True
End Sub

Неделю назад, когда число строк перевалило за 60000, стала вылетать ошибка:
Run time error ‘-2147417848 (80010108)’:
Method ‘Paste’ of object ‘_Worksheet’ failed

После нажатия Debug выделяется строка
ActiveSheet.Paste

При этом таки находится дубль 1-ой строки, но удалить никакую строку после этого невозможно — эксель просто не реагирует на попытку удаления строк и макрос поиска дублей больше не работает, а вот все остальные — работают. После перезагрузки экселя можно удалять строки, но при поиске дублей, ситуация повторяется.

Огромная просьба: помогите пожалуйста оптимизировать макрос, чтобы данная ошибка не возникала. Сколько сам не бился, не удалось исправить.

I have a macro which runs fine on my machine but when I try to run it on another machine it gives the following error.

Microsoft Visual Basic

Run-time Error -2147417848 (80010108)
Automation Error
The Object invoked has disconnected from its clients.

Undo's user avatar

Undo

25.4k37 gold badges110 silver badges129 bronze badges

asked Jun 23, 2010 at 10:53

Raja's user avatar

I found that the error is caused by ‘Freeze Panes’. If you are in the sliding part of the panel you get the crash, if you are in the frozen bit everything works fine.
The solution is: first change the active cell to a cell in the frozen pane, e.g. Range(«A1»).Activate

answered Feb 7, 2014 at 17:59

RobertOnStacko's user avatar

1

Here is a possible solution. I haven’t encountered the error myself so I’m not sure so…

Also, more detail would be helpful, what is the code surround the line where it errors? What is the code doing? Are both machines running the same version of Windows and Excel?

answered Aug 17, 2010 at 17:48

Icode4food's user avatar

Icode4foodIcode4food

8,46415 gold badges62 silver badges92 bronze badges

 

mazersw

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

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

#1

11.01.2021 15:18:48

Добрый день!

Записал макрос. На некоторых файлах все выполняется отлично а на некоторых выдает ошибку:

Цитата
Run-time error -2147417848 (80010108)
Method «Add» of object «ListObject» failed

Т.е. после запуска, просто зависает программ, нажимаешь закрыть, и Windows дает — перезапуск Excel ну  и после выводится ошибка VBA.

Подскажите пожалуйста кто с этим сталкивался, как можно исправить?

Код
Sub Макрос12()
' Макрос12 Макрос

    Sheets("Словарь").Select
   ' удаление строк
       Dim ra As Range, delra As Range
    Application.ScreenUpdating = False    ' отключаем обновление экрана
    ' ищем и удаляем строки, содержащие заданный текст
    ' (можно указать сколько угодно значений, и использовать подстановочные знаки)
    УдалятьСтрокиСТекстом = Array("на", "для", "идти", "если", "при", "это", "до", "о", "из", "надо", "за", "в", "с", "как", "какой", "к", "что", "по", "где")
    ' перебираем все строки в используемом диапазоне листа
    For Each ra In ActiveSheet.UsedRange.Rows
        ' перебираем все фразы в массиве
        For Each word In УдалятьСтрокиСТекстом
            ' если в очередной строке листа найден искомый текст
            If Not ra.Find(word, , xlValues, xlWhole) Is Nothing Then
                ' добавляем строку в диапазон для удаления
                If delra Is Nothing Then Set delra = ra Else Set delra = Union(delra, ra)
            End If
        Next word
    Next
 
    ' если подходящие строки найдены, то: (оставьте одну из 2 следующих строк)
    ' скрываем их If Not delra Is Nothing Then delra.EntireRow.Hidden = True    
    If Not delra Is Nothing Then delra.EntireRow.Delete    ' удаляем их
' удаление строк конец
' применение форматирование
    Columns("A:A").Select
    Selection.FormatConditions.AddColorScale ColorScaleType:=3
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    Selection.FormatConditions(1).ColorScaleCriteria(1).Type = _
        xlConditionValueLowestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(1).FormatColor
        .Color = 8109667
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(2).Type = _
        xlConditionValuePercentile
    Selection.FormatConditions(1).ColorScaleCriteria(2).Value = 50
    With Selection.FormatConditions(1).ColorScaleCriteria(2).FormatColor
        .Color = 8711167
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).ColorScaleCriteria(3).Type = _
        xlConditionValueHighestValue
    With Selection.FormatConditions(1).ColorScaleCriteria(3).FormatColor
        .Color = 7039480
        .TintAndShade = 0
    End With
    Columns("A:A").Select
    Selection.FormatConditions.AddDatabar
    Selection.FormatConditions(Selection.FormatConditions.Count).ShowValue = True
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1)
        .MinPoint.Modify newtype:=xlConditionValueAutomaticMin
        .MaxPoint.Modify newtype:=xlConditionValueAutomaticMax
    End With
    With Selection.FormatConditions(1).BarColor
        .Color = 15698432
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).BarFillType = xlDataBarFillSolid
    Selection.FormatConditions(1).Direction = xlContext
    Selection.FormatConditions(1).NegativeBarFormat.ColorType = xlDataBarColor
    Selection.FormatConditions(1).BarBorder.Type = xlDataBarBorderNone
    Selection.FormatConditions(1).AxisPosition = xlDataBarAxisAutomatic
    With Selection.FormatConditions(1).AxisColor
        .Color = 0
        .TintAndShade = 0
    End With
    With Selection.FormatConditions(1).NegativeBarFormat.Color
        .Color = 255
        .TintAndShade = 0
    End With
' применение форматирование конец
' добавление графика
    Range("A1:B1").Select
    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlBarOfPie
    ActiveChart.SetSourceData Source:=Range("Словарь!$A$1:$B$1")
    ActiveChart.SeriesCollection(1).Values = "=Словарь!$A$2:$A$20"
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.SeriesCollection(2).Name = "=Словарь!$B$1"
    ActiveChart.SeriesCollection(2).Values = "=Словарь!$B$2:$B$20"
    ActiveChart.SeriesCollection(2).XValues = "=Словарь!$B$2:$B$20"
    ActiveChart.ChartTitle.Select
    ActiveChart.ApplyLayout (6)
    ActiveChart.ChartTitle.Text = "ТОП20 униграмм в семантическом ядре"
    Selection.Format.TextFrame2.TextRange.Characters.Text = "ТОП20 униграмм в семантическом ядре"
    With Selection.Format.TextFrame2.TextRange.Characters(1, 14).ParagraphFormat
        .TextDirection = msoTextDirectionLeftToRight
        .Alignment = msoAlignCenter
    End With
    With Selection.Format.TextFrame2.TextRange.Characters(1, 14).Font
        .BaselineOffset = 0
        .Bold = msoTrue
        .NameComplexScript = "+mn-cs"
        .NameFarEast = "+mn-ea"
        .Fill.Visible = msoTrue
        .Fill.ForeColor.RGB = RGB(0, 0, 0)
        .Fill.Transparency = 0
        .Fill.Solid
        .Size = 18
        .Italic = msoFalse
        .Kerning = 12
        .Name = "+mn-lt"
        .UnderlineStyle = msoNoUnderline
        .Strike = msoNoStrike
    End With
    ActiveChart.ChartArea.Select
    ActiveSheet.Shapes("Диаграмма 1").ScaleWidth 1.48125, msoFalse, _
        msoScaleFromTopLeft
    ActiveSheet.Shapes("Диаграмма 1").ScaleHeight 1.4010414844, msoFalse, _
        msoScaleFromBottomRight
    ActiveSheet.Shapes("Диаграмма 1").ScaleHeight 1.1449815616, msoFalse, _
        msoScaleFromTopLeft
    ActiveSheet.Shapes("Диаграмма 1").ScaleWidth 1.0928271519, msoFalse, _
        msoScaleFromTopLeft
    ActiveChart.ChartGroups(1).SeriesLines.Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(19).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(18).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(17).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(16).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(15).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(14).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(13).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(12).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(11).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(10).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(9).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(8).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(7).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(6).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(5).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(4).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(3).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(2).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Points(1).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(1).Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(2).Points(20).DataLabel.Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(2).Points(19).DataLabel.Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.SeriesCollection(2).Points(18).DataLabel.Select
    ActiveSheet.ChartObjects("Диаграмма 1").Activate
    ActiveChart.ChartArea.Select
    ActiveSheet.Shapes("Диаграмма 1").IncrementLeft -96.75
    ActiveSheet.Shapes("Диаграмма 1").IncrementTop 9
    ActiveWindow.SmallScroll Down:=-80
    ActiveChart.ClearToMatchStyle
    ActiveChart.ChartStyle = 10
    ActiveChart.ClearToMatchStyle
' добавление графика конец

   '  форматирование таблицы
       Columns("A:C").Select
    ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A:$C"), , xlYes).Name = _
        "Таблица5"
       Range("Таблица5[[#Headers],[Униграмма]]").Select
    Range("Таблица5[[#Headers],[Униграмма]]").AddComment
    Range("Таблица5[[#Headers],[Униграмма]]").Comment.Visible = True
    Range("Таблица5[[#Headers],[Униграмма]]").Comment.Text Text:= _
        "Униграмма (лемма)  - это исходная форма слова. "
    'Selection.ShapeRange.IncrementLeft -62.25
    'Selection.ShapeRange.IncrementTop 58.5
    '  форматирование таблицы
End Sub

Еще проблема в том, что ошибка рандомная — то есть, то нет!
не знаю даже куда копать(((

 

Андрей_26

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

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

Добрый день!
Файл с примером приложите.

 

mazersw

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

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

#3

11.01.2021 16:00:10

Цитата
Андрей_26 написал:
Файл с примером приложите.

Прикрепленные файлы

  • Проект.xlsx (111.43 КБ)

 

Mershik

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

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

mazersw, мой вам совет описать задачу решаемую макросом, не всегда хочется людям изучать чужой макрос иногда проще и быстрее написать новый)

Не бойтесь совершенства. Вам его не достичь.

 

Дмитрий(The_Prist) Щербаков

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

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

Профессиональная разработка приложений для MS Office

#5

11.01.2021 16:22:53

Цитата
mazersw написал:
ошибка рандомная — то есть, то нет

так может и таблица с именем «Таблица5» то есть, то нет? Когда есть — ошибка(т.к. нельзя создать две таблицы с одинаковым именем), когда нет — и ошибки нет. Попробуйте добавлять с рандомным именем:

Код
ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A:$C"), , xlYes).Name = "NewTable" & ActiveSheet.ListObjects.Count + 1

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

mazersw

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

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

#6

12.01.2021 10:32:17

Ок попробую.  

Цитата
Mershik написал:  …совет описать задачу решаемую макросом

Макрос — просто создает диаграмму (график) и применяет нужное форматирование, и все…

 

RAN

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

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

#7

12.01.2021 11:01:38

А может есть смысл позволить Excel самому имя таблицы придумать?

Код
With ActiveSheet.ListObjects.Add(xlSrcRange, Range("$A:$C"), , xlYes)
    With .ListColumns("Униграмма").Range(1)
        .AddComment
        .Comment.Visible = True
        .Comment.Text Text:="Униграмма (лемма)  - это исходная форма слова. "
    End With
End With

I wrote a text file import routine that has worked fine until recently. 
It was the first routine that I created for this spreadsheet. 
It was fully tested and working properly and has had no modifications after it was completed. 
The problem arose some time later while I was writing other routines to process the imported data.  
All of the other routines work fine, but this one now produces the following error message when it runs:

Run-time error ‘-2147417848′(80010108)’:

Method ‘Delete’ of object ‘Range’ failed

The specific command that causes the error is:

               
Columns.Delete

When this error happens, whether it is Excel 2010 or 2013, Windows 7 or 8, it makes Excel unresponsive to input. 
I have to use the Task Manager to kill it.

I found a similar problem here on the forums where he was trying to delete rows.  He got the same results as me, but his solution does not work for me.  I will appreciate whetever help I can get. 

Here is the code:

Sub ImportInventoryFiles()
'
' ImportInventoryFile Macro
' Gets the context of the inventory text files and places them in their respective worksheets l (A1).
'
' Keyboard Shortcut: Ctrl+i
'
    Dim Path As String
    Dim FileName As String
    Dim Extension As String
    ' Delete extra sheets with the default Excel sheet name.
    sheetTot = Sheets.Count
    ' Eliminate any default sheets after the first sheet if they exist.
    For i = 2 To sheetTot
        If Left(Worksheets(i).Name, 5) = "Sheet" Then
            Application.DisplayAlerts = False
            Worksheets(i).Delete
            Application.DisplayAlerts = True
        End If
    Next i
    ' Now we can delete the first default sheet if there are more than one sheet left.
    ' Any sheets that are left after the first default sheet are probably records we need.
    ' If the only sheet left is a default sheet, it will be deleted after the user has
    ' selected files for processing.
    If Sheets.Count > 1 And Left(Worksheets(1).Name, 5) = "Sheet" Then
        Application.DisplayAlerts = False
        Worksheets(1).Delete
        Application.DisplayAlerts = True
    End If
    
    ' The user can select multiple .txt files.  After the file(s) have been selected, the
    ' macro parses out the file path to extract the file name sans the extension.  It then
    ' looks for a sheet name that matches the filename.  If it finds one, then it updates
    ' that sheet.  If not, then it creates a new sheet and names it with that filename.
    FileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt", , "Select all of the files that you want to import:", , True)
    If IsArray(FileToOpen) Then
        
        For f = 1 To UBound(FileToOpen)
            
            SlashLoc = InStrRev(FileToOpen(f), "")
            If SlashLoc > 0 Then
                Path = Left(FileToOpen(f), SlashLoc)
                l = Len(FileToOpen(f))
                FileName = Right(FileToOpen(f), l - SlashLoc)
                DotLoc = InStrRev(FileName, ".")
                If DotLoc > 0 Then
                    l = Len(FileName)
                    Extension = Right(FileName, l - DotLoc)
                    FileName = Left(FileName, DotLoc - 1)
                End If
            End If
            
            ' Look for a sheet name that matches the filename and activate it if found.
            totSheets = Sheets.Count
            i = 1
            sheetFound = False
            For i = 1 To totSheets
                If Worksheets(i).Name = FileName Then
                    Worksheets(FileName).Activate
                    sheetFound = True
                    Exit For
                End If
            Next i
            Sheets.Add
            If Not sheetFound Then
                If Left(Worksheets(1).Name, 5) <> "Sheet" Then
                ' If this single sheet is not a default sheet, then we need to create
                ' a new one.
                    Sheets.Add After:=Worksheets(Worksheets.Count)
                End If
                ' If that lone default sheet that we could not delete in the beginning
                ' is here, then it will be renamed and used for the current file.
                ActiveSheet.Name = FileName
                MsgBox FileName
            End If
            
            ' Clear the worksheet of any and all data.  We need a clean slate.
            Columns.Delete ' <------- This kills Excel for some reason.
            
            ' Drop the data from the text file into the work sheet starting from cell
            ' A:2.
            With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & FileToOpen(f), Destination:=Range("$A$2"))
                .Name = FileToOpen(f)
                .FieldNames = True
                .RowNumbers = False
                .FillAdjacentFormulas = False
                .PreserveFormatting = True
                .RefreshOnFileOpen = False
                .RefreshStyle = xlInsertDeleteCells
                .SavePassword = False
                .SaveData = True
                .AdjustColumnWidth = True
                .RefreshPeriod = 0
                .TextFilePromptOnRefresh = False
                .TextFilePlatform = 437
                .TextFileStartRow = 1
                .TextFileParseType = xlFixedWidth
                .TextFileTextQualifier = xlTextQualifierDoubleQuote
                .TextFileConsecutiveDelimiter = False
                .TextFileTabDelimiter = True
                .TextFileSemicolonDelimiter = False
                .TextFileCommaDelimiter = False
                .TextFileSpaceDelimiter = False
                .TextFileColumnDataTypes = Array(2)
                .TextFileTrailingMinusNumbers = True
                .Refresh BackgroundQuery:=False
            End With
            
            ' Put in column title.
            Range("A1").FormulaR1C1 = "Software Inventory"
            
            ' This data is for troubleshooting.  We can delete it when no longer needed.
            Range("C1").FormulaR1C1 = "Filename Information"
            Range("C1").Font.Bold = True
            Range("C2").FormulaR1C1 = FileToOpen(f)
            Range("C3").FormulaR1C1 = Path
            Range("C4").FormulaR1C1 = FileName
            Range("C5").FormulaR1C1 = Extension
            
            Call FormatWorksheet(True)
        Next f
        
    End If
    Call Summerize
    Range("A1").Select
     
End Sub

  • Remove From My Forums

 locked

Excel 2016 VBA Run-time error — Intermittent and Unpredictable

  • Question

  • I currently have a workbook that utilizes a visual basic macro. The workbook is set up with several sheets, used for various months, and within each sheet there is a table. Different users enter data into this
    table, and once they have the necessary information entered, the selection of a particular cells kicks off the macro that protects that row, and adds another row to the end of the table so that more information can be entered and previously entered data is
    protected from changes. This workbook worked very well in our previous version of Excel, which was Excel 2007. Since we upgraded to Excel 2016, sometimes the macro performs fine, but users have been encountering a «Run-time error ‘-2147417848 (80010108)’:
    Automation error The object invoked has disconnected from its clients», sometimes. The error doesn’t always happen on the same row or after the same number of entries. Sometimes users can enter 5 lines of data and then get the error, sometimes users can
    enter 300+ lines of data and then encounter the error. I’m trying to understand what is causing the issue, why it is only sometimes occurring, and how I can modify the macro so that the error is no longer an issue. Any help would be appreciated.

    Sub Prepared()

    ActiveSheet.Unprotect

    ActiveSheet.ListObjects(1).ListRows.Add AlwaysInsert:=True

    ‘Insert preparers Windows Username in active cell

    Selection = Application.UserName

    ‘Lock prepared row

    Range(«D» & ActiveCell.Row & «:M» & ActiveCell.Row).Select

    Selection.Locked = True

    ActiveSheet.Protect

    End Sub

    • Moved by

      Friday, February 24, 2017 2:10 AM

Понравилась статья? Поделить с друзьями:
  • Rtf в word на русском
  • Run time error 13 type mismatch ошибка как исправить excel
  • Rtf в word как создать таблицу
  • Run time error 13 type mismatch in vba excel
  • Rtf в word как редактировать