Run time error 2147417848 80010108 vba excel

  • 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

 

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) Щербаков

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

Сообщений: 13997
Регистрация: 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

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

Сообщений: 7081
Регистрация: 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

  • #1

I’m at wits end…

I have two ActiveX control buttons on a Worksheet («Servers_Test»): btnAddWindowsLinux and btnDeleteWindowsLinux.

Here are the following VBA macros, respectively:

Rich (BB code):

Option Explicit


Private Sub btnAddWindowsLinux_Click()

Dim servers As Worksheet
Dim serverTable As ListObject
Dim serverTableRow As ListRow
Dim serverTableRows As ListRows

Set servers = ThisWorkbook.Worksheets("Servers_Test")
Set serverTable = servers.ListObjects("WindowsLinux")
Set serverTableRow = serverTable.ListRows.Add(AlwaysInsert:=True) ' Reference line where error(s) are occuring for adding a row to the table

If serverTable.ListRows.Count > 1 Then
    btnDeleteWindowsLinux.Enabled = True
End If


End Sub



Private Sub btnDeleteWindowsLinux_Click()

Dim servers As Worksheet
Dim serverTable As ListObject
Dim serverTableRow As ListRow
Dim serverTableRows As ListRows

 Set servers = ActiveWorkbook.Worksheets("Servers_Test")
 Set serverTable = servers.ListObjects("WindowsLinux")
 Set serverTableRows = serverTable.ListRows
 
If serverTableRows.Count > 1 Then
    serverTable.ListRows(serverTable.ListRows.Count).Delete ' Reference line where error(s) are occuring for adding a row to the table
        If serverTable.ListRows.Count > 1 Then
            btnDeleteWindowsLinux.Enabled = True
        Else
            btnDeleteWindowsLinux.Enabled = False
        End If
    
    End If

This is a completely random error message that appears. Even if I add multiple rows, then delete them (using the control buttons), then go to add more, I get the Run-time error ‘-2147417848 (80010108)’: «Method ‘Add’ of object ‘ListRows’ failed» window. Following a «Debug» selection (and having VBA identify the line of code that is causing the error), when I stop the macro and press the «Add New Server» button (btnAddWindowsLinux), I get a new error message: «Run-time error ‘1004’: Application-defined or object-defined error».

I’ve been to NUMEROUS Excel help sites with absolutely no luck. Can anyone please help me eliminate these random, inconvenient, and unproductive errors from occuring?

Thank you, in advance, for any assistance you can provide.

— Matt

Last edited by a moderator: Jul 19, 2016

0 / 0 / 0

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

Сообщений: 48

1

18.07.2013, 21:58. Показов 20280. Ответов 102


Добрый день.

Долгое время работал с макросом в Эксель 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-ой строки, но удалить никакую строку после этого невозможно — эксель просто не реагирует на попытку удаления строк и макрос поиска дублей больше не работает, а вот все остальные — работают. После перезагрузки экселя можно удалять строки, но при поиске дублей, ситуация повторяется.

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

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



0



  1. 04-28-2018, 03:20 AM


    #1

    Post Run time error -2147417848 (80010108) Method «_range» of object «_worksheet» failed.

    Hi All,

    New to this forum and VBA. I am currently making a calculator and it was working fine for sometime but now I am receiving an error «Runtime error -2147417848 (80010108) method _range of object _worksheet failed». Where as the only command that is running is to display a number from a cell into the textbox.
    Major portion of my work is completed and this thing is now causing a heck of a problem for me and I am really sick and tired of dealing with this. Any type of help will be appreciated.

    Regards,
    Aoxolom

    Following is code attached:

    Private Sub TextBox8_Change()
    
    IF KeyAscii > Asc("9") Or KeyAscii < Asc("0") Then
              If KeyAscii = Asc("-") Then
                    If InStr(1, Me.TextBox8.Text, "-") > 0 Or _
                     Me.TextBox8.SelStart > 0 Then KeyAscii = 0
                ElseIf KeyAscii = Asc(".") Then
                     If InStr(1, Me.TextBox8.Text, ".") > 0 Then KeyAscii = 0
                Else
                    KeyAscii = 0
              End If
    End If
        
     If IsNumeric(Application.Sheets("Main Calculator").Range("D19").Value) = False Then '(cause of error)
            TextBox8.Text = "INVALID"
    
    Else
             TextBox8.Value = Application.Sheets("Main Calculator").Range("D19").Value
             TextBox8.Value = Round(TextBox8.Text, 3)
    End If
    
    End Sub

    Last edited by SamT; 04-28-2018 at 06:08 AM.


  2. 04-28-2018, 06:13 AM


    #2

    «Application.Sheets» refers to the Active workbook. Is the correct workbook active? Can you replace «Application.Sheets» with «Workbooks(BookName).Sheets(….»

    I expect the student to do their homework and find all the errrors I leeve in.


  3. 04-28-2018, 12:04 PM


    #3

    Thank you for the reply SamT.
    I changed the value for it but the error still continues. The thing is that the program runs for the 1st time in some cases but after resetting it the error pops up again.


  4. 04-28-2018, 12:55 PM


    #4

    Where is KeyAscii coming from? It doesn’t seem to be a VBA key word.

    Also the Change Event occurs aftweer the KeyUp eent, so it’s too late to capture the pressed Key’s value.

    Try something like this

    Private PreviousTextBox8Value As String
    
    Private Sub TextBox8_Change()
    Dim LastChar As String
    
    With Me
      LastChar = Right(.TextBox8, 1)
      If Not IsNumeric(LastChar) Then
              If Asc(LastChar) = Asc("-") Then
                    If InStr(1, .TextBox8.Text, "-") > 0 Or _
                     .TextBox8.SelStart > 0 Then TextBox8 = PreviousTextBox8Value
                ElseIf LastChar = "." Then
                     If InStr(1, .TextBox8.Text, ".") > 0 Then .TextBox8 = PreviousTextBox8Value
                Else
                    .TextBox8 = PreviousTextBox8Value
              End If
      Else: PreviousTextBox8Value = .TextBox8
      End If
    End With
    '
    'More code
    End Sub

    Just be sure you reset PreviousTextBox8Value to «» When done

    I expect the student to do their homework and find all the errrors I leeve in.


  5. 04-28-2018, 11:34 PM


    #5

    Again thanks for the reply Sam.

    I changed the declaration of textbox8 from «change» to «afterupdate» and the code seems to run flawless now. Thanks for all the help and will bother you again if the issue comes up.

    Regards,
    aoxolom


  6. 06-27-2018, 11:22 PM


    #6

    Newbie whose also getting the error and not sure why

    Hi Guys

    I also need help with a Run-time error ‘-2147352571(80020005)’: Type Mismatch

    I can’t figure out how to fix this issue. My Script is as follows :

    Private Sub CommandButton1_Click()
    
    
    Dim con As Variant
    Dim cmd As Variant
    Dim StoredProc As String
    Dim WSP1 As Worksheet
    Set con = CreateObject("ADODB.Connection")
    Set cmd = CreateObject("ADODB.Command")
    
    
    Set parm = cmd.CreateParameter("(atsymbol)ChosenBDM", adVarChar, , 4, TextBox1.Value())
    Set parm2 = cmd.CreateParameter("(atsymbol)NewBDM", adVarChar, , 4, TextBox2.Value())
    
    
    Application.DisplayStatusBar = True
    Application.StatusBar = "Contacting SQL Server..."
    
    
        ServerName = "----" ' Enter your server name here
        DatabaseName = "----" ' Enter your database name here
        UserID = "--" ' Enter your user ID here
        Password = "----" ' Enter your password here
        StoredProcedure = "[New_BDM_Creation]" ' Enter Stored Procedure here
    
    
    ' Log into our SQL Server, and run the Stored Procedure
    con.Open "Provider=SQLOLEDB;Data Source=" & ServerName & ";Initial Catalog=" & DatabaseName & ";User ID=" & UserID & ";Password=" & Password & ";Trusted_Connection=no"
    cmd.ActiveConnection = con
    
    
    Application.StatusBar = "Running stored procedure..."
    
    
        cmd.CommandTimeout = 900
        Set cmd = cmd.Execute(parm, parm2, StoredProcedure) ------> Error appears here
    
    
    Set cmd = Nothing
    con.Close
    Set con = Nothing
    
    
    Application.StatusBar = "Data successfully updated."
    
    
    End Sub


  7. 06-28-2018, 06:33 AM


    #7

    It’s more effective to start a new topic instead of just tagging on to a previous one, even if you think that they’re somewhat related

    ———————————————————————————————————————

    Paul

    Remember: Tell us WHAT you want to do, not HOW you think you want to do it

    1. Use [CODE] ….[/CODE ] Tags for readability
    [CODE]PasteYourCodeHere[/CODE ] — (or paste your code, select it, click [#] button)
    2. Upload an example
    Go Advanced / Attachments — Manage Attachments / Add Files / Select Files / Select the file(s) / Upload Files / Done
    3. Mark the thread as [Solved] when you have an answer
    Thread Tools (on the top right corner, above the first message)
    4. Read the Forum FAQ, especially the part about cross-posting in other forums
    http://www.vbaexpress.com/forum/faq…._new_faq_item3


  1. 07-01-2016, 05:26 AM


    #1

    Vassen is offline


    Registered User


    RunTime Error 2147417848 -Method insert of object Range Failed

    Hi,
    When running below Code in my excel sheet , Error message >> Run time error 214741848 (80010108) >> Method «Insert» of object «Range» failed.
    Please help

    Last edited by JBeaucaire; 07-11-2016 at 04:52 PM.

    Reason: Added missing CODE tags. Please read and follow the Forum Rules, link above in the menu bar. Thanks.


  2. 07-01-2016, 05:59 AM


    #2

    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Trevor Shuttleworth — Excel Aid

    I dream of a better world where chickens can cross the road without having their motives questioned

    ‘Being unapologetic means never having to say you’re sorry’ John Cooper Clarke


  3. 07-01-2016, 06:01 AM


    #3

    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Is the sheet protected? You’d get an Insert error for that scenario, though not necessarily the one you quote.


  4. 07-01-2016, 07:34 AM


    #4

    Vassen is offline


    Registered User


    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Hi TMS,
    No i do not have any lock cell, nor sheet protection. I have tried your new code but still same error message :

    Last edited by JBeaucaire; 07-11-2016 at 04:53 PM.


  5. 07-01-2016, 07:45 AM


    #5

    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Suggest you post a sample of the workbook (that demonstrates the problem), if you can.

    The code works in a newly created simple workbook, so it’s not the code per se.


  6. 07-01-2016, 08:26 AM


    #6

    Vassen is offline


    Registered User


    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Hi TMS,
    Thanks for your quick response, i have uploaded a sample of the file(I had to cut the file as it is 39 MB.
    Please note that with this file i had one trial it works and fails again at second attempt. Excel file is blocked. Had to close and reopen file , tried again same error message


  7. 07-01-2016, 09:08 AM


    #7

    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Works for me. Executed code several times. The only issue that I had is that there are links in the file, presumably to the original. So, when I copy the rows, I get a File Open dialogue box … I just press Escape to continue.

    For example: [Supply Chain Version 29 Dec 2015.xlsm]NLM_LT’!$N$114.. Clearly, I don’t have the relevant workbook OR worksheet.


  8. 07-11-2016, 01:16 AM


    #8

    Vassen is offline


    Registered User


    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Hi TMS,
    Thanks for your prompt reply and sorry to attend your thread only today as I was ill whole last week. Still problem when working on original file. Same error appears
    The workbook i am working with consist of 20 worksheets which are all linked. Can the links between these sheets be a cause, can the size of the sheet (10 KB) be a problem. As there are formulas in the cells to be copied and insert, can the VBA actions be separated into 3 as follows:
    1 >> Copy and insert Column A to S (as all are values)
    2 >> Copy and paste special column T to XX in the inserted column in action 1 in T to XX
    3 >> Execute formulas in inserted cell after action 2
    Again apologies for late reply. Thanks for your help
    Vassen


  9. 07-11-2016, 08:49 AM


    #9

    Vassen is offline


    Registered User


    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Hi TMS,
    You were right, it works withe the workbook containing only this worksheet, as I test same with the workbook with 20 worksheets linked, it gives ERROR message, How can this problem be overcome. Thanks for your help
    Vassen


  10. 07-11-2016, 04:54 PM


    #10

    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Maybe add this near the top of the macro:

    Worth a try…

    _________________
    Microsoft MVP 2010 — Excel
    Visit: Jerry Beaucaire’s Excel Files & Macros

    If you’ve been given good help, use the icon below to give reputation feedback, it is appreciated.
    Always put your code between code tags. [CODE]

    your code here [/CODE]

    ?None of us is as good as all of us? — Ray Kroc
    ?Actually, I *am* a rocket scientist.? — JB (little ones count!)


  11. 07-12-2016, 03:48 AM


    #11

    Vassen is offline


    Registered User


    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Hi JBeaucaire,
    Can you please precise what you mean by «Near the Top». Is it just before «ActiveCell.EntireRow.Copy. Note that it is not only giving the ERROR message but is also blocking the workbook, I have to close, do not save and re open to be able to work again
    Thanks for your help
    Vassen


  12. 07-13-2016, 07:03 AM


    #12

    Vassen is offline


    Registered User


    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Hi JBeaucaire,TMS
    I have tried but still same error message and it blocks the sheet,
    Please help
    Vassen


  13. 07-13-2016, 07:34 AM


    #13

    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Don
    Please remember to mark your thread ‘Solved’ when appropriate.


  14. 07-13-2016, 08:05 AM


    #14

    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Not sure what else to suggest. The code works, at least, it works in a new workbook/worksheet. So, the implication is that it is something to do with the data in the live file rather than a problem with the code.

    As you cannot insert a row, I’m guessing that Excel sees data on the last row of the sheet. Maybe you have inadvertently copied a formula down to the last row. Or you have formatting or Conditional Formatting or Data Validation.

    If you press Ctrl-End, which cell/row/column is selected? If it is row 1048576 that’s probably the problem. In which case, you need to delete all the rows between the end of the real data and the last row. Select all the rows and use the Delete icon on the Ribbon, not the Delete key. Then save the file.


  15. 07-14-2016, 05:26 AM


    #15

    Vassen is offline


    Registered User


    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    Hi TMS,xlnitwit,
    Thanks for your help.
    Vassen


  16. 07-14-2016, 06:58 AM


    #16

    Re: RunTime Error 2147417848 -Method insert of object Range Failed

    You’re welcome.

    If you are satisfied with the solution(s) provided, please mark your thread as Solved.

    New quick method:
    Select Thread Tools-> Mark thread as Solved. To undo, select Thread Tools-> Mark thread as Unsolved.

    Or you can use this way:

    How to mark a thread Solved
    Go to the first post
    Click edit
    Click Go Advanced
    Just below the word Title you will see a dropdown with the word No prefix.
    Change to Solved
    Click Save

    You may also want to consider thanking those people who helped you by clicking on the little star at the bottom left of their reply to your question.


Понравилась статья? Поделить с друзьями:
  • Run time error 2147319779
  • Run time error 2147221040 800401d0
  • Run time error 2147023170 800706be
  • Run time error 2146697208 800c0008 как исправить
  • Run time error 19 file or function is not found перевод