Ошибка при вызове метода контекста range произошла исключительная ситуация 0x800a03ec

  

mxs089

17.03.15 — 16:02

в excel включаю запись макроса, выделяю несколько ячеек с зажатым ctrl, смотрю что получилось:

Range(«W13:Y13,AA13:AC13»).Select

пишу в 1с:

Документ.Листы[0].Range(«W13:Y13,AA13:AC13»).Select();

ругается на метод Range, не правильно использую?

  

bolobol

1 — 17.03.15 — 16:12

Читаем справку — первая ссылка в яндексе:

Application.Union(Range(«Sheet1!A1:B2»), Range(«Sheet1!C3:D4»))

  

manyak

2 — 17.03.15 — 16:16

а какую ошибку выдает?

  

mxs089

3 — 17.03.15 — 16:18

Ошибка при вызове метода контекста (Range)

    Документ.Листы[0].Range(«W13:Y13,AA13:AC13»).Select();

по причине:

Произошла исключительная ситуация (0x800a03ec)

  

manyak

4 — 17.03.15 — 16:23

в документе у тебя должен лежать excel

попробуй

документ.Worksheets(«лист1»).Range(«A1,C3,E6,G8»).Select

или

документ.Worksheets(0).Range(«A1,C3,E6,G8»).Select

  

manyak

5 — 17.03.15 — 16:23

ну и про () в конце ессно не забудь :)

  

mxs089

6 — 17.03.15 — 16:40

WorkBooks = EXCEL.WorkBooks.Open(ИмяФайла);

WorkBooks.Worksheets(0).Range(«A1,C3,E6,G8»).Select();

Ошибка при вызове метода контекста (Worksheets)

    WorkBooks.Worksheets(0).Range(«A1,C3,E6,G8»).Select();

по причине:

Произошла исключительная ситуация (0x8002000b)

  

manyak

7 — 17.03.15 — 16:42

по имени листа пробывал обращаться?

  

manyak

8 — 17.03.15 — 16:43

Worksheets(«имя_листа»)

  

mxs089

9 — 17.03.15 — 16:46

(8) получилось по имени, теперь ошибка RANGE

Произошла исключительная ситуация (0x800a03ec)

  

mxs089

10 — 17.03.15 — 16:46

(3)

  

manyak

11 — 17.03.15 — 16:47

может у тебя куча excel мало ли не прибитых в памяти висит?

перегрузись от греза по дальше :)

так то код святая простота  — должен робить

  

mxs089

12 — 17.03.15 — 17:15

удалось выделить одну ячейку, если указываю список — происходит ошибка, вопрос, как выделить несколько ячеек?

  

bolobol

13 — 17.03.15 — 17:17

(12) Ты читать-то умеешь? Ответ в первом сообщении дан.

  

icrocodile

14 — 17.03.15 — 17:23

(12) вот так :

WorkBooks.Worksheets(1).Range(«A1;B1;C1;D1;E1;F1;G1;H1;I1»).Select();

  

icrocodile

15 — 17.03.15 — 17:24

и да, нумерация листов начинается с 1 :)

  

mxs089

16 — 17.03.15 — 17:25

(14) спасибо! да, разделитель ;

  

mxs089

17 — 18.03.15 — 14:31

я так понимаю там есть ограничение на количество выделенных ячеек, более 18 не получается выделить, я вижу есть еще метод Area, кто нить использовал?

Эксель.COMОбъект.Selection.Areas(«W13:Y13;AA13:AC13»)

Ошибка

по причине:

Типы не совпадают (1)

I am getting «HRESULT: 0x800A03EC» error when running Excel add-in with following code:

Excel.Range rng = ActiveSheet.Cells[x, y] as Excel.Range;                
string before = rng.Value2; 
string cleanV = System.Text.RegularExpressions.Regex.Replace(before, @"s+", "");
rng.set_Value(cleanV);

When error happens X and Y are set to 1, thus Excel range is not violated.
I searched extensively and tried a number of ways of setting the cell value (eg. Cells[x,y], range.set_Value()) but am at loss why this error happens and how to avoid it.

Any help is greatly appreciated.

Below are exception details:


System.Runtime.InteropServices.COMException was unhandled by user code
  HResult=-2146827284
  Message=Exception from HRESULT: 0x800A03EC
  Source=""
  ErrorCode=-2146827284
  StackTrace:
       at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       at Microsoft.Office.Interop.Excel.Range.set_Value(Object RangeValueDataType, Object value)
       at ImportValidation.ThisAddIn.removeAnySpaces(Int32 x, Int32 y) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 354
       at ImportValidation.ThisAddIn.ReadHeaders(Hashtable columnAddress) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 123
       at ImportValidation.ThisAddIn.mapColumns() in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 493
       at ImportValidation.Ribbon1.button6_Click(Object sender, RibbonControlEventArgs e) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationRibbon1.cs:line 55
       at Microsoft.Office.Tools.Ribbon.RibbonPropertyStorage.ControlActionRaise(IRibbonControl control)
       at Microsoft.Office.Tools.Ribbon.RibbonPropertyStorage.ButtonClickCallback(RibbonComponentImpl component, Object[] args)
       at Microsoft.Office.Tools.Ribbon.RibbonManagerImpl.Invoke(RibbonComponentCallback callback, Object[] args)
       at Microsoft.Office.Tools.Ribbon.RibbonMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at Microsoft.Office.Tools.Ribbon.RibbonManagerImpl.System.Reflection.IReflect.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
  InnerException: 

I am getting «HRESULT: 0x800A03EC» error when running Excel add-in with following code:

Excel.Range rng = ActiveSheet.Cells[x, y] as Excel.Range;                
string before = rng.Value2; 
string cleanV = System.Text.RegularExpressions.Regex.Replace(before, @"s+", "");
rng.set_Value(cleanV);

When error happens X and Y are set to 1, thus Excel range is not violated.
I searched extensively and tried a number of ways of setting the cell value (eg. Cells[x,y], range.set_Value()) but am at loss why this error happens and how to avoid it.

Any help is greatly appreciated.

Below are exception details:


System.Runtime.InteropServices.COMException was unhandled by user code
  HResult=-2146827284
  Message=Exception from HRESULT: 0x800A03EC
  Source=""
  ErrorCode=-2146827284
  StackTrace:
       at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       at Microsoft.Office.Interop.Excel.Range.set_Value(Object RangeValueDataType, Object value)
       at ImportValidation.ThisAddIn.removeAnySpaces(Int32 x, Int32 y) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 354
       at ImportValidation.ThisAddIn.ReadHeaders(Hashtable columnAddress) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 123
       at ImportValidation.ThisAddIn.mapColumns() in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 493
       at ImportValidation.Ribbon1.button6_Click(Object sender, RibbonControlEventArgs e) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationRibbon1.cs:line 55
       at Microsoft.Office.Tools.Ribbon.RibbonPropertyStorage.ControlActionRaise(IRibbonControl control)
       at Microsoft.Office.Tools.Ribbon.RibbonPropertyStorage.ButtonClickCallback(RibbonComponentImpl component, Object[] args)
       at Microsoft.Office.Tools.Ribbon.RibbonManagerImpl.Invoke(RibbonComponentCallback callback, Object[] args)
       at Microsoft.Office.Tools.Ribbon.RibbonMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at Microsoft.Office.Tools.Ribbon.RibbonManagerImpl.System.Reflection.IReflect.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
  InnerException: 

I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

Edit:

If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):

Exception from HRESULT: 0x800A03EC

and/or

Old format or invalid type library

SOLUTION 1:


To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.

//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
  oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
  System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}

SOLUTION 2:


Another solution that could work, create a 1033 directory under Microsoft OfficeOffice11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.

Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:

yourRange.Value2 = «10/10/09»

Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:

October 10, 2009
September 10, 2009
October 9, 2010

Icon Ex Номер ошибки: Ошибка 0x800A03EC
Название ошибки: Excel ? Error Object Returned Error Code 0X800A03Ec
Описание ошибки: Ошибка 0x800A03EC: Возникла ошибка в приложении Microsoft Excel. Приложение будет закрыто. Приносим извинения за неудобства.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Excel
Относится к: Windows XP, Vista, 7, 8, 10, 11

Проверка «Excel ? Error Object Returned Error Code 0X800A03Ec»

Обычно люди ссылаются на «Excel ? Error Object Returned Error Code 0X800A03Ec» как на ошибку времени выполнения (ошибку). Разработчики, такие как Microsoft Corporation, обычно проходят через несколько контрольных точек перед запуском программного обеспечения, такого как Microsoft Excel. К сожалению, такие проблемы, как ошибка 0x800A03EC, могут быть пропущены, и программное обеспечение будет содержать эти проблемы при выпуске.

Некоторые пользователи могут столкнуться с сообщением «Excel ? Error Object Returned Error Code 0X800A03Ec» при использовании Microsoft Excel. Когда это происходит, конечные пользователи могут сообщить Microsoft Corporation о наличии ошибок «Excel ? Error Object Returned Error Code 0X800A03Ec». Разработчик сможет исправить свой исходный код и выпустить обновление на рынке. Эта ситуация происходит из-за обновления программного обеспечения Microsoft Excel является одним из решений ошибок 0x800A03EC ошибок и других проблем.

Как триггеры Runtime Error 0x800A03EC и что это такое?

Сбой устройства или Microsoft Excel обычно может проявляться с «Excel ? Error Object Returned Error Code 0X800A03Ec» в качестве проблемы во время выполнения. Следующие три наиболее значимые причины ошибок выполнения ошибки 0x800A03EC включают в себя:

Ошибка 0x800A03EC Crash — Ошибка 0x800A03EC является хорошо известной, которая происходит, когда неправильная строка кода компилируется в исходный код программы. Это возникает, когда Microsoft Excel не реагирует на ввод должным образом или не знает, какой вывод требуется взамен.

Утечка памяти «Excel ? Error Object Returned Error Code 0X800A03Ec» — если есть утечка памяти в Microsoft Excel, это может привести к тому, что ОС будет выглядеть вялой. Есть некоторые потенциальные проблемы, которые могут быть причиной получения проблем во время выполнения, с неправильным кодированием, приводящим к бесконечным циклам.

Ошибка 0x800A03EC Logic Error — Логическая ошибка вызывает неправильный вывод, даже если пользователь дал действительные входные данные. Это видно, когда исходный код Microsoft Corporation содержит недостаток в обработке данных.

Такие проблемы Excel ? Error Object Returned Error Code 0X800A03Ec обычно вызваны повреждением файла, связанного с Microsoft Excel, или, в некоторых случаях, его случайным или намеренным удалением. Основной способ решить эти проблемы вручную — заменить файл Microsoft Corporation новой копией. Более того, поддержание чистоты реестра и его оптимизация позволит предотвратить указание неверного пути к файлу (например Excel ? Error Object Returned Error Code 0X800A03Ec) и ссылок на расширения файлов. По этой причине мы рекомендуем регулярно выполнять очистку сканирования реестра.

Типичные ошибки Excel ? Error Object Returned Error Code 0X800A03Ec

Частичный список ошибок Excel ? Error Object Returned Error Code 0X800A03Ec Microsoft Excel:

  • «Ошибка Excel ? Error Object Returned Error Code 0X800A03Ec. «
  • «Недопустимая программа Win32: Excel ? Error Object Returned Error Code 0X800A03Ec»
  • «Извините, Excel ? Error Object Returned Error Code 0X800A03Ec столкнулся с проблемой. «
  • «К сожалению, мы не можем найти Excel ? Error Object Returned Error Code 0X800A03Ec. «
  • «Отсутствует файл Excel ? Error Object Returned Error Code 0X800A03Ec.»
  • «Проблема при запуске приложения: Excel ? Error Object Returned Error Code 0X800A03Ec. «
  • «Не удается запустить Excel ? Error Object Returned Error Code 0X800A03Ec. «
  • «Отказ Excel ? Error Object Returned Error Code 0X800A03Ec.»
  • «Ошибка пути программного обеспечения: Excel ? Error Object Returned Error Code 0X800A03Ec. «

Эти сообщения об ошибках Microsoft Corporation могут появляться во время установки программы, в то время как программа, связанная с Excel ? Error Object Returned Error Code 0X800A03Ec (например, Microsoft Excel) работает, во время запуска или завершения работы Windows, или даже во время установки операционной системы Windows. При появлении ошибки Excel ? Error Object Returned Error Code 0X800A03Ec запишите вхождения для устранения неполадок Microsoft Excel и чтобы HelpMicrosoft Corporation найти причину.

Корень проблем Excel ? Error Object Returned Error Code 0X800A03Ec

Заражение вредоносными программами, недопустимые записи реестра Microsoft Excel или отсутствующие или поврежденные файлы Excel ? Error Object Returned Error Code 0X800A03Ec могут создать эти ошибки Excel ? Error Object Returned Error Code 0X800A03Ec.

Точнее, ошибки Excel ? Error Object Returned Error Code 0X800A03Ec, созданные из:

  • Недопустимая или поврежденная запись Excel ? Error Object Returned Error Code 0X800A03Ec.
  • Файл Excel ? Error Object Returned Error Code 0X800A03Ec поврежден от вирусной инфекции.
  • Excel ? Error Object Returned Error Code 0X800A03Ec ошибочно удален или злонамеренно программным обеспечением, не связанным с приложением Microsoft Excel.
  • Другое приложение, конфликтующее с Excel ? Error Object Returned Error Code 0X800A03Ec или другими общими ссылками.
  • Microsoft Excel (Excel ? Error Object Returned Error Code 0X800A03Ec) поврежден во время загрузки или установки.

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

Форум 1С : Все вопросы » Загрузка данных в 1С Загрузка данных в 1С

ЮлияЮ
25.05.2018 08:27 Прочитано: 3883

При загрузке данных из Eхcel выдаёт ошибку «Произошла исключительная ошибка (0х800а03ес)», что сделать? Я новичок, ещё не очень разбираюсь в программе.

Yandex
Возможно, вас также заинтересует

Реклама на портале

all4cf
28.05.2018 10:57 Ответ № 1

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

Подсказка: Для выделения Кода используйте (в редакторе).

Вы не можете отправить комментарий анонимно, пожалуйста войдите или зарегистрируйтесь.

[ Главная | FAQ: Все | 7.х | 8.х | 8.2 УП | 8.3 | Видео | Files | Forum | Freelance | Поиск | Реклама на HelpF.pro | Обратная связь ]
HelpF.pro [old Help1C.com] 2009-2023 Все материалы, размещенные на сайте, добавлены посетителями сайта или взяты из свободных источников. Подробнее…

Здравствуйте! Подскажите, пожалуйста! Загружаю из Excel данные, хочу обратиться к именованной области, выдает следующую ошибку: «Ошибка при вызове метода контекста (Cells): Произошла исключительная ситуация (0x800a03ec)
ФайлСтрок = Excel.Cells(2,1).SpecialCells(21).Row;
по причине:
Произошла исключительная ситуация (0x800a03ec)»

Процедура ОсновныеДействияФормыЗагрузить(Кнопка)

НомерКолонкиАртикул = ЭлементыФормы.ТабличныйДокумент.Область(«R2C1»;
НомерКолонкиНаименованияТовара = ЭлементыФормы.ТабличныйДокумент.Область(«R2C2»;
НомерКолонкиЕдиницаИзмерения = ЭлементыФормы.ТабличныйДокумент.Область(«R2C3»;
НомерКолонкиСтрана = ЭлементыФормы.ТабличныйДокумент.Область(«R2C4»;

//В разных версиях Excel получаются по-разному, поэтому сначала определим версию Excel
Excel = новый COMОбъект(«Excel.Application»;

Версия = Лев(Excel.Version,Найти(Excel.Version,».»-1);
Если Версия = «8» тогда
ФайлСтрок = Excel.Cells.CurrentRegion.Rows.Count;
ФайлКолонок = Макс(Excel.Cells.CurrentRegion.Columns.Count, 13);
Иначе
ФайлСтрок = Excel.Cells(2,1).SpecialCells(21).Row;
ФайлКолонок = Excel.Cells(2,1).SpecialCells(21).Column;
Конецесли;

// Выбираем данные из файла
Для а = Excel.Cells(2,1).SpecialCells(21).Row по ФайлСтрок Цикл

//Полуим данные из соответсвующих ячеек
Артикул = СокрЛП(Excel.Cells(а,Артикул).Value);
НаименованиеТовара = СокрЛП(Excel.Cells(а,НомерКолонкиНаименованияТовара).Value);
ЕдиницаИзмерения = СокрЛП(Excel.Cells(а,НомерКолонкиЕдиницаИзмерения).Value);

Товар = Справочники.Номенклатура.ПустаяСсылка();

// Ищем товар в справочнике по коду
Товар = Справочники.Номенклатура.НайтиПоКоду.Артикул;

// Если не нашли по коду, то ищем по наименованию
Если Товар.Пустая() Тогда
Товар = Справочники.Номенклатура.НайтиПоНаименованию.Наименование;
Конецесли;

//Если не нашли создаем новый
Если Товар.Пустая() Тогда
Товар = Справочники.Номенклатура.СоздатьЭлемент();
Товар.Наименование = НаименованиеТовара;
Товар.Артикул = Артикул;
Товар.БазоваяЕдиницаИзмерения = ЕдиницаИзмерения;
Товар.СтранаПроисхождения = НомерКолонкиСтрана;
Товар.Записать();
Конецесли;
КонецЦикла;

КонецПроцедуры

Сильно не пинать, только учусь. Делаю выгрузку прайсов в ексель. Есть заминка на куске кода Колонка = Прайс.Столбцы.Найти(«Примечание»); погуглил текст ошибки — несоответствие типов данных. но какое у меня может быть не соответствие не могу понять. передаю область, передаю ссылку, передаю представление ссылки — все поля текстовые. Подскажите кто в курсе, в какую сторону рыть хотя бы, а лучше носом ткните в ошибку)

а где это делается? В модуле объекта? Что есть ссылка в данном контексте?

это делается в модуле формы. ссылка формируется из «константы» + «код номенклатуры» + «.html» ссылка на номенклатуру на сайте.

ws.Hyperlinks.add нормально относится к первому параметру? Это же объект, не текст?

к первому параметру относится нормально. в отладчике проверяю в ws.cells(НомерСтроки + СчетчикТекРаздела, Колонка.НомерКолонки) все нормально.

Ошибка при вызове метода Add или Cells? Думается мне, что всё-таки дело в кривых параметрах именно Cells…

+6 Помести результат вызова Cells в переменную, тогда однозначно будет понятно, в чём ошибка: range = ws.cells(НомерСтроки + СчетчикТекРаздела, Колонка.НомерКолонки);

да я же говорю в cells все ок. в отладчике глядел — получается область, адрес ячейки верный. голову уже сломал — не могу понять где бок.

На вопрос из ответа мы так и не узнали.

Ошибки как таковой нет. отладчик проходит код и двигает дальше. только в єкселе в ячейках вместо данных ошибка «Произошла исключительная ситуация (0x800a03ec)»

а что макрос екселевский по этому поводу напишет? если гиперссылку лапками в клеточки под его микрофон?

Тэги: 1С 8

Комментарии доступны только авторизированным пользователям

I am getting «HRESULT: 0x800A03EC» error when running Excel add-in with following code:

Excel.Range rng = ActiveSheet.Cells[x, y] as Excel.Range;                
string before = rng.Value2; 
string cleanV = System.Text.RegularExpressions.Regex.Replace(before, @"s+", "");
rng.set_Value(cleanV);

When error happens X and Y are set to 1, thus Excel range is not violated.
I searched extensively and tried a number of ways of setting the cell value (eg. Cells[x,y], range.set_Value()) but am at loss why this error happens and how to avoid it.

Any help is greatly appreciated.

Below are exception details:


System.Runtime.InteropServices.COMException was unhandled by user code
  HResult=-2146827284
  Message=Exception from HRESULT: 0x800A03EC
  Source=""
  ErrorCode=-2146827284
  StackTrace:
       at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       at Microsoft.Office.Interop.Excel.Range.set_Value(Object RangeValueDataType, Object value)
       at ImportValidation.ThisAddIn.removeAnySpaces(Int32 x, Int32 y) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 354
       at ImportValidation.ThisAddIn.ReadHeaders(Hashtable columnAddress) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 123
       at ImportValidation.ThisAddIn.mapColumns() in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationThisAddIn.cs:line 493
       at ImportValidation.Ribbon1.button6_Click(Object sender, RibbonControlEventArgs e) in c:UsersdshevelevDocumentsVisual Studio 2012ProjectsImportValidationImportValidationRibbon1.cs:line 55
       at Microsoft.Office.Tools.Ribbon.RibbonPropertyStorage.ControlActionRaise(IRibbonControl control)
       at Microsoft.Office.Tools.Ribbon.RibbonPropertyStorage.ButtonClickCallback(RibbonComponentImpl component, Object[] args)
       at Microsoft.Office.Tools.Ribbon.RibbonManagerImpl.Invoke(RibbonComponentCallback callback, Object[] args)
       at Microsoft.Office.Tools.Ribbon.RibbonMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at Microsoft.Office.Tools.Ribbon.RibbonManagerImpl.System.Reflection.IReflect.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
  InnerException: 

Добрый день ! Подскажите с чем может быть связана следующая ошибка: Произошла исключительная ситуация (0x800a03ec)

Из 1С (считай VBA) открываю эксель-файл и пытаюсь получить Адрес именованного диапазона для последующей записи/чтения

Код
    Адр = Sheet.Range(ИменованныйДиапазон).Address;   // ИменованныйДиапазон = "Критерии"

Получаю сообщение:

Цитата
Ошибка при вызове метода контекста (Range)
по причине: Произошла исключительная ситуация (0x800a03ec)

Этот же код работает без ошибок для других Именованных Диапазонов Эксель-файла. («блок», «грейд» и т.д.)
Но для конкретно этого диапазона (ИменованныйДиапазон = «Критерии») получаю ошибку. Причем это обычный диапазон 2х2
Может я его как то неправильно создал ? Или есть какие то опции в Экселе …

   mxs089

17.03.15 — 16:02

в excel включаю запись макроса, выделяю несколько ячеек с зажатым ctrl, смотрю что получилось:

Range(«W13:Y13,AA13:AC13»).Select

пишу в 1с:

Документ.Листы[0].Range(«W13:Y13,AA13:AC13»).Select();

ругается на метод Range, не правильно использую?

   bolobol

1 — 17.03.15 — 16:12

Читаем справку — первая ссылка в яндексе:

Application.Union(Range(«Sheet1!A1:B2»), Range(«Sheet1!C3:D4»))

   manyak

2 — 17.03.15 — 16:16

а какую ошибку выдает?

   mxs089

3 — 17.03.15 — 16:18

Ошибка при вызове метода контекста (Range)

    Документ.Листы[0].Range(«W13:Y13,AA13:AC13»).Select();

по причине:

Произошла исключительная ситуация (0x800a03ec)

   manyak

4 — 17.03.15 — 16:23

в документе у тебя должен лежать excel

попробуй

документ.Worksheets(«лист1»).Range(«A1,C3,E6,G8»).Select

или

документ.Worksheets(0).Range(«A1,C3,E6,G8»).Select

   manyak

5 — 17.03.15 — 16:23

ну и про () в конце ессно не забудь :)

   mxs089

6 — 17.03.15 — 16:40

WorkBooks = EXCEL.WorkBooks.Open(ИмяФайла);

WorkBooks.Worksheets(0).Range(«A1,C3,E6,G8»).Select();

Ошибка при вызове метода контекста (Worksheets)

    WorkBooks.Worksheets(0).Range(«A1,C3,E6,G8»).Select();

по причине:

Произошла исключительная ситуация (0x8002000b)

   manyak

7 — 17.03.15 — 16:42

по имени листа пробывал обращаться?

   manyak

8 — 17.03.15 — 16:43

Worksheets(«имя_листа»)

   mxs089

9 — 17.03.15 — 16:46

(8) получилось по имени, теперь ошибка RANGE

Произошла исключительная ситуация (0x800a03ec)

   mxs089

10 — 17.03.15 — 16:46

(3)

   manyak

11 — 17.03.15 — 16:47

может у тебя куча excel мало ли не прибитых в памяти висит?

перегрузись от греза по дальше :)

так то код святая простота  — должен робить

   mxs089

12 — 17.03.15 — 17:15

удалось выделить одну ячейку, если указываю список — происходит ошибка, вопрос, как выделить несколько ячеек?

   bolobol

13 — 17.03.15 — 17:17

(12) Ты читать-то умеешь? Ответ в первом сообщении дан.

   icrocodile

14 — 17.03.15 — 17:23

(12) вот так :

WorkBooks.Worksheets(1).Range(«A1;B1;C1;D1;E1;F1;G1;H1;I1»).Select();

   icrocodile

15 — 17.03.15 — 17:24

и да, нумерация листов начинается с 1 :)

   mxs089

16 — 17.03.15 — 17:25

(14) спасибо! да, разделитель ;

  

mxs089

17 — 18.03.15 — 14:31

я так понимаю там есть ограничение на количество выделенных ячеек, более 18 не получается выделить, я вижу есть еще метод Area, кто нить использовал?

Эксель.COMОбъект.Selection.Areas(«W13:Y13;AA13:AC13»)

Ошибка

по причине:

Типы не совпадают (1)

I am getting HRESULT: 0x800A03EC on Worksheet.range method. Number of rows are more than 70K. Office 2007.

Code:

Microsoft.Office.Interop.Excel.Range neededRange
    = currentWS.Range[cell.Cells[1, 1], cell.Cells[nRowCount, nColumnCount]];

Here my rowcount is more than 65530 . Breaks on this function. I have observed that it breaks only when row count goes more than 65530.

asked Aug 17, 2011 at 21:31

Cannon's user avatar

CannonCannon

2,70710 gold badges45 silver badges86 bronze badges

6

This problem occurs if you are using a backwards compatible sheet (a .xls) instead of a .xlsx

To allow sheets to be opened in pre office 2007 version it can’t contain more than 65k rows. You can check the number of rows in your sheet by using ctrl+arrowdown till you hit the bottom. If you try to get a range larger than that number of rows it will create an error

answered Aug 18, 2011 at 13:45

Eddy's user avatar

EddyEddy

5,31024 silver badges40 bronze badges

5

We were receiving the same. The exception was

Stacktrace: at Microsoft.Office.Interop.Excel._Workbook.SaveAs(Object Filename, Object FileFormat, Object Password, Object WriteResPassword, Object
ReadOnlyRecommended, Object CreateBackup, XlSaveAsAccessMode AccessMode, Object ConflictResolution, Object AddToMru, Object TextCodepage, Object Text
VisualLayout, Object Local)`

with an inner exception of

Exception from HRESULT: 0x800A03EC 2012-11-01 10:37:59`

We were able to resolve the problem with information from this post, which I quote here for convenience…

  1. Login to the server as a administrator.
  2. Go to «Start» -> «Run» and enter «taskmgr»
  3. Go to the process tab in task manager and check «Show Processes from all
    users»
  4. If there are any «Excel.exe» entries on the list, right click on the
    entry and select «End Process»
  5. Close task manager.
  6. Go to «Start» -> «Run» and enter «services.msc»
  7. Stop the service automating Excel if it is running.
  8. Go to «Start» -> «Run» and enter «dcomcnfg»
  9. This will bring up the component services window, expand out «Console
    Root» -> «Computers» -> «DCOM Config»
  10. Find «Microsoft Excel Application» in the list of components.
  11. Right click on the entry and select «Properties»
  12. Go to the «Identity» tab on the properties dialog.
  13. Select «The interactive user.»
  14. Click the «OK» button.
  15. Switch to the services console
  16. Start the service automating Excel
  17. Test you application again.

Mo Patel's user avatar

Mo Patel

2,3114 gold badges22 silver badges37 bronze badges

answered Nov 1, 2012 at 10:11

John Fitzpatrick's user avatar

John FitzpatrickJohn Fitzpatrick

4,1977 gold badges47 silver badges71 bronze badges

4

I encountered this issue.

Discovered that somewhere in my code I was asking it to count starting from 0 (as you would in a C# code).

Turns out Excel counting starts at 1.

answered Feb 2, 2015 at 10:47

Cald's user avatar

CaldCald

2012 silver badges6 bronze badges

0

Looking at the various responses above, and drawing on my own recent experience (I got this error code doing something completely unrelated — setting Application.Calculation) I conclude that the same error code is used to indicate multiple unrelated problems. So @Garreh you should probably be asking a new question (not that anyone will be able to help based on the error code alone). I’ve seen the same thing working with Word interop from C#, where the same HRESULT seems to be used for almost every kind of error. I’ve never found any satisfactory Microsoft documentation on what the codes might mean.

answered Feb 11, 2013 at 17:29

Hugh W's user avatar

Hugh WHugh W

6301 gold badge10 silver badges33 bronze badges

1

This could also be caused if you have no room on the partition you are saving to.

I checked my HD and foind it was maxed. Moving some un-needed files to a different partition resolved my problem.

answered Nov 7, 2012 at 15:33

Patrickmoe's user avatar

PatrickmoePatrickmoe

511 silver badge1 bronze badge

Simply, the excel file is corrupt.
Best solution is change/repair the file.(make a copy of the existing file and rename it)

answered Oct 23, 2012 at 5:17

Sonio's user avatar

SonioSonio

391 bronze badge

I don’t understand the issue. But here is the thing that solved my issue.

Go to Excel Options > Save > Save Files in this format > Select «Excel Workbook(*.xlsx)». Previously, my WorkBooks were opening in [Compatibuility Mode] And now they are opening in normal mode. Range function works fine with that.

answered Aug 18, 2011 at 16:10

Cannon's user avatar

CannonCannon

2,70710 gold badges45 silver badges86 bronze badges

3

Just FYI, got the error trying to apply row style….

wSheet.Rows(y).Style = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red)

answered Jun 9, 2016 at 16:26

htm11h's user avatar

htm11hhtm11h

1,7298 gold badges46 silver badges103 bronze badges

Not being able to reply to/endorse this answer, so posting here:

Indeed, the format of the source/destination ranges when moving data from one range to another might cause this error as well.

In my case, the range I wanted to copy contained a date formatted column, and the column contained one cell with an invalid date value (it was not even formatted due to its value, which was a negative integer). So the copy operation between the two ranges was halting at the said cell yielding the very error message discussed here.

The solution in my case was to use Range.Value2 instead of Range.Value, which caused Excel to bypass formatting the cell as a date (more details here). However, this will render your date and time columns to display as integers and decimals. You will, however, be able to change the formats to the desired ones if you know where to expect the date and time values by setting their Range/Column/Cell.NumberFormat property accordingly.

Community's user avatar

answered Jun 23, 2016 at 11:00

Teodor Constantinescu's user avatar

This isn’t directly answering the question, but I was getting this error when opening an xlsx file. The problem was that I was using forward slashes in my file path. See also https://stackoverflow.com/a/24635904/5932003. It used to work in previous versions of Excel, but not with Version 1711 (Build 8730.2127).

I was able to diagnose the problem using IDispatch->Invoke(…, EXCEPINFO, …). The EXCEPINFO object contained a useful description of what went wrong. I was in C++ land, but I suspect that C# code similar to this SO post will do the trick: Packaging IDispatch Invoke with Parameters in C# (with DISPPARAMS).

answered Jan 2, 2018 at 16:03

kostasvs's user avatar

kostasvskostasvs

3914 silver badges12 bronze badges

0

I received this error code 0x800A03EC when trying to save an Excel file created within my .Net application in VS 2017. I changed the Excel.Application object property Visible=True and let it run until the point of failure. Tried to finish the steps manually in Excel and then discovered I could not save the file because of missing folder permissions. I added the Write permission to the folder, and the error went away.

answered Jan 3, 2019 at 17:39

MarkF's user avatar

MarkFMarkF

1131 silver badge10 bronze badges

1

For others like me, who have the same exception:

It can also happen if you try to pass a null value instead of Missing.Value (or Type.Missing)

e.g.

Worksheet worksheet = ...;
return worksheet.Range["A1", null]; //This call generates the error 0x800A03EC

return worksheet.Range["A1", Missing.Value]; //This works correctly

answered May 6, 2019 at 9:32

Ruben Giaquinto's user avatar

in 2021, when i got this problem. the reason actually is:

for a Excel range or cell, i was trying to add/delete comment directly without checking whether there is a comment binding with it or not.

error code is:

if ( comments_string.Length != 0)
{     range.AddComment( comments_string);
}

working code is:

if ( comments_string.Length != 0)
{     if (range.Comment != null) range.Comment.Delete();
     range.AddComment(comments_string);
}

answered Feb 12, 2021 at 13:26

Mike Xue's user avatar

EDIT: THIS IS WAY BETTER!!!
You don’t need that old function, sorry. Just do as follows:

Microsoft.Office.Interop.Excel.Range neededRange = currentWS.Range["A1", ((Microsoft.Office.Interop.Excel.Range)currentWS.Cells[nRowCount, nColumnCount])];

That should work like a charm. And for future reference, put the relevant code that you are using inside of your question. Don’t make people ask for it in comments. I imagine that’s why you got downvoted.

answered Aug 17, 2011 at 22:25

k.schroeder31's user avatar

k.schroeder31k.schroeder31

8012 gold badges8 silver badges15 bronze badges

4

I had an error with exact code when I tried to assigned array of cells to range.Value. In my case it was the problem with wrong data format. The cell’s data format was set as DATE but the user made an error and instead of «20.02.2013» entered date «20.02.0213». The Excel’s COM object refused taking year ‘0213’ and threw exception with this error.

answered Feb 21, 2015 at 21:00

Evgeny Sobolev's user avatar

I had the same error code when executing the following statement:

sheet.QueryTables.Add("TEXT" & Path.GetFullPath(fileName), "1:1", Type.Missing)

The reason was the missing semicolon (;) after «TEXT».

Here is the correct one:

sheet.QueryTables.Add("TEXT;" & Path.GetFullPath(fileName), "1:1", Type.Missing)

answered Feb 2, 2017 at 14:08

Beppe Serra's user avatar

I got this exception because I typed:

ws.get_Range("K:K").EntireColumn.AutoFit();
ws.get_Range("N:N").EntireColumn.AutoFit();
ws.get_Range("0:0").EntireColumn.AutoFit();

See a mistake?
Hint: Excel is accepting indexing from 1, but not from 0 as C# does.

answered Mar 10, 2017 at 10:14

Pedro's user avatar

PedroPedro

11 bronze badge

0

I got this error because I tried to rename a sheet with too many characters

answered May 29, 2017 at 8:56

Blobby's user avatar

0

I agree with Hugh W post «I conclude that the same error code is used to indicate multiple unrelated problems»

Other posts have not mentioned that this error occurs frequently if the worksheet is locked. While I haven’t tested every scenario, it seems that anything that you can not do in excel when a worksheet is locked with throw this error if you attempt to do it via VSTO/Com while the sheet is locked. E.G. Changing any style artifact (font, font size, colour, underline), changing the Excel Validation, changing the column widths, row heights, formulas

answered Sep 8, 2017 at 0:29

JimbobTheSailor's user avatar

JimbobTheSailorJimbobTheSailor

1,3861 gold badge11 silver badges21 bronze badges

I resolved this issue by using the code below. Please do not use other parameters in these functions.

mWorkBook = xlApp.Workbooks.Open(FilePath)

mWorkBook.Save();

RESOLVED

N.K's user avatar

N.K

1,5952 gold badges19 silver badges31 bronze badges

answered Apr 25, 2018 at 7:40

Pankaj Garg's user avatar

Seems like this i s a pretty generic error for «something went wrong» with the operation you attempted. I have observed that will also occur if you have a formula error and are assigning that formula into a cell. E.g. «=fubar()»

answered Apr 17, 2019 at 19:39

Dan Sorak's user avatar

I’ve come across it several different times and every time it was always some error with either duplicating a tab name or in this current case it just occurred because I simply had a typo in the get_Range where I tried to get a Cell by number and number instead of the letter and number.
Drove me crazy because the error pointed me to a few lines down but I had commented out all of the creation of the other sheets above the «error line» and the ones in the line and below were created with no issue.
Happened to scan up a few lines above and saw that I put 6 + lastword, C + lastrow in my get_Range statement and of course you can’t have a cell starting with a number it’s always letter than number.

Dino's user avatar

Dino

7,67911 gold badges45 silver badges83 bronze badges

answered Sep 30, 2019 at 7:09

Robert L Taylor's user avatar

I ran in to the same error. For me it was while trying to set a CountIf and CountIfs respectively that I got the error.

After some trial an error I found out it was an issue I had with all formulas using multiple parameters.

It turns out that the parameter separator «;» (semicolon), which I use in excel is not the correct one for me to use in code behind. If I use «,» (comma) in stead, the formula is correctly used.
Note: When viewed in Excel afterwards, it is shown as «;» (semicolon).

My trial and error process included trying to set a bunch of different formulas, and this was the ‘fix’ I ended up with.
I am running an English windows, but I am located in Denmark, I have no idea if there is some kind of localization involved with my issue.

CultureInfo.CurrentCulture.TextInfo.ListSeparator is «;», and this works correctly for separating validator rule values.
Perhaps this is the reason why my parameter separator is something else.

Anyways; the formula could be wrong because you need to use a different parameter separator character.

answered Jul 28, 2021 at 8:14

aliceraunsbaek's user avatar

I had this same error code. Turns out a comment here helped me. Count does not start from 0. The commented out line was throwing this error.

string cell = (string)range.Cells[3, 3].Value;
This line worked fine

string QuestionID = (string)range.Cells[1, 0].Value;This line threw this error

answered Dec 22, 2021 at 17:21

daniel jacobsen's user avatar

1

I know this is old but I had the same error when trying to set a spreadsheet range as follows:

rngSumFormula = mxlWorksheet.Range(strFormulaRange)

There were plenty of mxlWorksheet.Range statements before this one but it failed every time. It turned out, after a ton of digging that the difference between my range value in strFormulaRange and the other values is that it had commas in the range i.e. «B2,C2,D2:E2». Before this statement all the ranges values simple had a colon i.e. «D2:E2».

So why was this an issue? Because I don’t use comma as my default separator in Windows 10 instead I use a pipe character (|) as I deal with a lot of SQL bulk loads of description fields which contain lots of commas that aren’t separators. Once I changed my default separator back to a comma my error disappeared.

This probably won’t help very many people as I don’t think separator changes are very common but since it was my solution I wanted to share. Just for reference you change your separator in Windows 10 here:

Region Settings>Additional Date, Time & Regional Settings>Change Date, Time or Number Formats>Additional Settings and then scroll down to List separator.

answered Aug 18, 2022 at 18:07

GunnerFan420's user avatar

For me the answer came when trying to post a Notes column in the Excel sheet. The sheet would not accept it. I kept getting this error. I thought it might be a certain character or something. If it is, I don’t know what. So I just cut it off at 250. I don’t know what the size limit actually is?!… but for my purpose in this report it’s not really important:

The ones that are empty I’ve already filled with ‘Missing.Value’.

            if (dr[c] != null && dr[c].ToString() != "")
            {
                string t = dr[c].ToString().Replace("t", "").Replace("|", ":").Replace("/", "-").Replace("n", " ").Trim();
                if (t.Length > 250)
                    t = t.Substring(0, 250);
                arr[r, c] = t;
            }

answered May 23 at 21:26

Robert Koernke's user avatar

This type of error can also occur when the excel file is corrupted for some reason

answered Dec 1, 2017 at 9:00

Arun's user avatar

ArunArun

438 bronze badges

  • Ошибка при вызове метода контекста вызватьhttpметод
  • Ошибка при вызове метода контекста quit
  • Ошибка при вызове метода контекста выгрузить метод недоступен на клиенте
  • Ошибка при вызове метода контекста previewfile1c
  • Ошибка при вызове метода контекста вывести построительотчета вывести табличныйдокумент