- Remove From My Forums
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
-
Moved by
mazersw Пользователь Сообщений: 90 |
#1 11.01.2021 15:18:48 Добрый день! Записал макрос. На некоторых файлах все выполняется отлично а на некоторых выдает ошибку:
Т.е. после запуска, просто зависает программ, нажимаешь закрыть, и Windows дает — перезапуск Excel ну и после выводится ошибка VBA. Подскажите пожалуйста кто с этим сталкивался, как можно исправить?
Еще проблема в том, что ошибка рандомная — то есть, то нет! |
||||
Андрей_26 Пользователь Сообщений: 647 |
Добрый день! |
mazersw Пользователь Сообщений: 90 |
#3 11.01.2021 16:00:10
Прикрепленные файлы
|
||
Mershik Пользователь Сообщений: 8277 |
mazersw, мой вам совет описать задачу решаемую макросом, не всегда хочется людям изучать чужой макрос иногда проще и быстрее написать новый) Не бойтесь совершенства. Вам его не достичь. |
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 13997 Профессиональная разработка приложений для MS Office |
#5 11.01.2021 16:22:53
так может и таблица с именем «Таблица5» то есть, то нет? Когда есть — ошибка(т.к. нельзя создать две таблицы с одинаковым именем), когда нет — и ошибки нет. Попробуйте добавлять с рандомным именем:
Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||||
mazersw Пользователь Сообщений: 90 |
#6 12.01.2021 10:32:17 Ок попробую.
Макрос — просто создает диаграмму (график) и применяет нужное форматирование, и все… |
||
RAN Пользователь Сообщений: 7081 |
#7 12.01.2021 11:01:38 А может есть смысл позволить Excel самому имя таблицы придумать?
|
||
-
#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 | ||
|
Неделю назад, когда число строк перевалило за 60000, стала вылетать ошибка:
Run time error ‘-2147417848 (80010108)’:
Method ‘Paste’ of object ‘_Worksheet’ failed
После нажатия Debug выделяется строка
ActiveSheet.Paste
При этом таки находится дубль 1-ой строки, но удалить никакую строку после этого невозможно — эксель просто не реагирует на попытку удаления строк и макрос поиска дублей больше не работает, а вот все остальные — работают. После перезагрузки экселя можно удалять строки, но при поиске дублей, ситуация повторяется.
Огромная просьба: помогите пожалуйста оптимизировать макрос, чтобы данная ошибка не возникала. Сколько сам не бился, не удалось исправить.
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
-
04-28-2018, 03:20 AM
#1
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,
AoxolomFollowing 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.
-
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.
-
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.
-
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.
-
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
-
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
-
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
-
07-01-2016, 05:26 AM
#1
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 helpLast 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.
-
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
-
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.
-
07-01-2016, 07:34 AM
#4
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.
-
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.
-
07-01-2016, 08:26 AM
#6
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
-
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.
-
07-11-2016, 01:16 AM
#8
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
-
07-11-2016, 08:49 AM
#9
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
-
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 & MacrosIf 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!)
-
07-12-2016, 03:48 AM
#11
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
-
07-13-2016, 07:03 AM
#12
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
-
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.
-
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.
-
07-14-2016, 05:26 AM
#15
Registered User
Re: RunTime Error 2147417848 -Method insert of object Range Failed
Hi TMS,xlnitwit,
Thanks for your help.
Vassen
-
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 SaveYou 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.