Error: Ошибка 91 — Чтобы создать объектную переменную, нужно выполнить два шага. Сначала вы должны объявить объектную переменную. Затем вы должны назначить действительную ссылку на объектную переменную с помощью оператора Set. Аналогично, блок With … End With должен быть инициализирован путем выполнения
В этой статье представлена ошибка с номером Ошибка 91, известная как Переменная объекта или переменная блока не задана, описанная как Чтобы создать объектную переменную, нужно выполнить два шага. Сначала вы должны объявить объектную переменную. Затем вы должны назначить действительную ссылку на объектную переменную с помощью оператора Set. Аналогично, блок With … End With должен быть инициализирован путем выполнения
О программе Runtime Ошибка 91
Время выполнения Ошибка 91 происходит, когда Windows дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.
Определения (Бета)
Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!
- Назначить — что-то, что связано с операцией присваивания, т. е. процессом изменения содержимого переменной для отражения некоторого заданного значения.
- Блок < / b> — этот тег записывается, потому что он может относиться ко многим различным вещам в зависимости от использования с ним других тегов.
- Объявить — используйте этот тег для вопросов, связанных с declare, который обычно предназначен для объявления переменных, операторов и т. д.
- Object — объект — это любой объект, которым можно управлять с помощью команд на языке программирования.
- Набор — набор — это набор, в котором ни один элемент не повторяется, который может иметь возможность перечислять свои элементы в соответствии с критерием упорядочения «упорядоченный набор» или не сохранять порядок «неупорядоченный набор». «.
- Переменная — ЭТО НЕОБХОДИМО ; ИСПОЛЬЗУЙТЕ КОНКРЕТНЫЕ ЯЗЫКОВЫЕ ТЭГИ, ЕСЛИ ПРИМЕНИМО
< li> Ссылка. Ссылка — это значение, которое позволяет программе косвенно обращаться к определенным данным, таким как переменная или запись, в памяти компьютера или в каком-либо другом запоминающем устройстве.
Симптомы Ошибка 91 — Переменная объекта или переменная блока не задана
Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.
Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.
(Только для примера)
Причины Переменная объекта или переменная блока не задана — Ошибка 91
При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.
Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.
Методы исправления
Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.
Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.
Обратите внимание: ни ErrorVault.com, ни его авторы не несут ответственности за результаты действий, предпринятых при использовании любого из методов ремонта, перечисленных на этой странице — вы выполняете эти шаги на свой страх и риск.
Метод 1 — Закройте конфликтующие программы
Когда вы получаете ошибку во время выполнения, имейте в виду, что это происходит из-за программ, которые конфликтуют друг с другом. Первое, что вы можете сделать, чтобы решить проблему, — это остановить эти конфликтующие программы.
- Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
- Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
- Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
- Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.
Метод 2 — Обновите / переустановите конфликтующие программы
Использование панели управления
- В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
- В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
- Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
- В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
- Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.
Использование других методов
- В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
- В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
- Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
- Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.
Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.
Заражение вирусом, вызывающее ошибку выполнения на вашем компьютере, необходимо немедленно предотвратить, поместить в карантин или удалить. Убедитесь, что вы обновили свою антивирусную программу и выполнили тщательное сканирование компьютера или запустите Центр обновления Windows, чтобы получить последние определения вирусов и исправить их.
Метод 4 — Переустановите библиотеки времени выполнения
Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.
- Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
- Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
- Загрузите последний распространяемый пакет от Microsoft и установите его.
Метод 5 — Запустить очистку диска
Вы также можете столкнуться с ошибкой выполнения из-за очень нехватки свободного места на вашем компьютере.
- Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
- Вы также можете очистить кеш и перезагрузить компьютер.
- Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C
- Щелкните «Свойства», а затем — «Очистка диска».
Метод 6 — Переустановите графический драйвер
Если ошибка связана с плохим графическим драйвером, вы можете сделать следующее:
- Откройте диспетчер устройств и найдите драйвер видеокарты.
- Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.
Метод 7 — Ошибка выполнения, связанная с IE
Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:
- Сбросьте настройки браузера.
- В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
- Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
- Отключить отладку скриптов и уведомления об ошибках.
- В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
- Установите флажок в переключателе.
- Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.
Если эти быстрые исправления не работают, вы всегда можете сделать резервную копию файлов и запустить восстановление на вашем компьютере. Однако вы можете сделать это позже, когда перечисленные здесь решения не сработают.
Другие языки:
How to fix Error 91 (Object variable or With block variable not set) — There are two steps to creating an object variable. First you must declare the object variable. Then you must assign a valid reference to the object variable using the Set statement. Similarly, a With…End With block must be initialized by executing the
Wie beheben Fehler 91 (Objektvariable oder With-Blockvariable nicht gesetzt) — Es gibt zwei Schritte, um eine Objektvariable zu erstellen. Zuerst müssen Sie die Objektvariable deklarieren. Anschließend müssen Sie der Objektvariablen mit der Set-Anweisung eine gültige Referenz zuweisen. Ebenso muss ein With…End With-Block initialisiert werden, indem die
Come fissare Errore 91 (Variabile oggetto o Con variabile di blocco non impostata) — Ci sono due passaggi per creare una variabile oggetto. Per prima cosa devi dichiarare la variabile oggetto. Quindi è necessario assegnare un riferimento valido alla variabile oggetto utilizzando l’istruzione Set. Allo stesso modo, un blocco With…End With deve essere inizializzato eseguendo il comando
Hoe maak je Fout 91 (Object variabele of met blok variabele niet ingesteld) — Er zijn twee stappen om een objectvariabele te maken. Eerst moet u de objectvariabele declareren. Vervolgens moet u een geldige verwijzing naar de objectvariabele toewijzen met behulp van de Set-instructie. Op dezelfde manier moet een With…End With-blok worden geïnitialiseerd door de
Comment réparer Erreur 91 (Variable objet ou Variable avec bloc non définie) — Il y a deux étapes pour créer une variable d’objet. Vous devez d’abord déclarer la variable objet. Ensuite, vous devez affecter une référence valide à la variable objet à l’aide de l’instruction Set. De même, un bloc With…End With doit être initialisé en exécutant la commande
어떻게 고치는 지 오류 91 (개체 변수 또는 With 블록 변수가 설정되지 않았습니다.) — 개체 변수를 만드는 데는 두 단계가 있습니다. 먼저 객체 변수를 선언해야 합니다. 그런 다음 Set 문을 사용하여 개체 변수에 유효한 참조를 할당해야 합니다. 마찬가지로 With…End With 블록은 다음을 실행하여 초기화해야 합니다.
Como corrigir o Erro 91 (Variável de objeto ou com variável de bloco não definida) — Existem duas etapas para criar uma variável de objeto. Primeiro você deve declarar a variável do objeto. Em seguida, você deve atribuir uma referência válida à variável de objeto usando a instrução Set. Da mesma forma, um bloco With … End With deve ser inicializado executando o
Hur man åtgärdar Fel 91 (Objektvariabel eller Med blockvariabel ej inställd) — Det finns två steg för att skapa en objektvariabel. Först måste du deklarera objektvariabeln. Sedan måste du tilldela en giltig referens till objektvariabeln med Set -satsen. På samma sätt måste ett With … End With block initieras genom att köra
Jak naprawić Błąd 91 (Zmienna obiektu lub Zmienna blokowa nie jest ustawiona) — Tworzenie zmiennej obiektowej składa się z dwóch kroków. Najpierw musisz zadeklarować zmienną obiektu. Następnie należy przypisać prawidłowe odwołanie do zmiennej obiektu za pomocą instrukcji Set. Podobnie blok With…End With musi zostać zainicjowany przez wykonanie
Cómo arreglar Error 91 (Variable de objeto o con variable de bloque no establecida) — Hay dos pasos para crear una variable de objeto. Primero debes declarar la variable de objeto. Luego debe asignar una referencia válida a la variable de objeto usando la instrucción Set. De manera similar, un bloque With … End With debe inicializarse ejecutando el
Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.
Следуйте за нами:
Последнее обновление:
24/10/22 12:05 : Пользователь Windows 10 проголосовал за то, что метод восстановления 4 работает для него.
Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.
ШАГ 1:
Нажмите здесь, чтобы скачать и установите средство восстановления Windows.
ШАГ 2:
Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.
ШАГ 3:
Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.
СКАЧАТЬ СЕЙЧАС
Совместимость
Требования
1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.
ID статьи: ACX09108RU
Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000
Логотипы Microsoft и Windows® являются зарегистрированными торговыми марками Microsoft. Отказ от ответственности: ErrorVault.com не связан с Microsoft и не заявляет о такой связи. Эта страница может содержать определения из https://stackoverflow.com/tags по лицензии CC-BY-SA. Информация на этой странице представлена исключительно в информационных целях. © Copyright 2018
Номер ошибки: | Ошибка во время выполнения 91 | |
Название ошибки: | Object variable or With block variable not set | |
Описание ошибки: | There are two steps to creating an object variable. First you must declare the object variable. Then you must assign a valid reference to the object variable using the Set statement. Similarly, a With…End With block must be initialized by executing the | |
Разработчик: | Microsoft Corporation | |
Программное обеспечение: | Windows Operating System | |
Относится к: | Windows XP, Vista, 7, 8, 10, 11 |
Основы «Object variable or With block variable not set»
Это наиболее распространенное условие «Object variable or With block variable not set», известное как ошибка времени выполнения (ошибка). Разработчики, такие как Microsoft Corporation, обычно проходят через несколько контрольных точек перед запуском программного обеспечения, такого как Windows Operating System. К сожалению, инженеры являются людьми и часто могут делать ошибки во время тестирования, отсутствует ошибка 91.
В выпуске последней версии Windows Operating System может возникнуть ошибка, которая гласит: «There are two steps to creating an object variable. First you must declare the object variable. Then you must assign a valid reference to the object variable using the Set statement. Similarly, a With…End With block must be initialized by executing the ». Если происходит «Object variable or With block variable not set», разработчикам будет сообщено об этой проблеме, хотя отчеты об ошибках встроены в приложение. Затем Microsoft Corporation исправляет эти дефектные записи кода и сделает обновление доступным для загрузки. Таким образом при выполнении обновления программного обеспечения Windows Operating System, он будет содержать исправление для устранения проблем, таких как ошибка 91.
Почему происходит ошибка времени выполнения 91?
Сбой во время запуска Windows Operating System или во время выполнения, как правило, когда вы столкнетесь с «Object variable or With block variable not set». Вот три наиболее заметные причины ошибки ошибки 91 во время выполнения происходят:
Ошибка 91 Crash — она называется «Ошибка 91», когда программа неожиданно завершает работу во время работы (во время выполнения). Это возникает, когда Windows Operating System не реагирует на ввод должным образом или не знает, какой вывод требуется взамен.
Утечка памяти «Object variable or With block variable not set» — Когда Windows Operating System обнаруживает утечку памяти, операционная система постепенно работает медленно, поскольку она истощает системные ресурсы. Потенциальные триггеры могут быть «бесконечным циклом», или когда программа выполняет «цикл» или повторение снова и снова.
Ошибка 91 Logic Error — Логические ошибки проявляются, когда пользователь вводит правильные данные, но устройство дает неверный результат. Это может произойти, когда исходный код Microsoft Corporation имеет уязвимость в отношении передачи данных.
Как правило, такие Microsoft Corporation ошибки возникают из-за повреждённых или отсутствующих файлов Object variable or With block variable not set, а иногда — в результате заражения вредоносным ПО в настоящем или прошлом, что оказало влияние на Windows Operating System. Большую часть проблем, связанных с данными файлами, можно решить посредством скачивания и установки последней версии файла Microsoft Corporation. Кроме того, некоторые ошибки Object variable or With block variable not set могут возникать по причине наличия неправильных ссылок на реестр. По этой причине для очистки недействительных записей рекомендуется выполнить сканирование реестра.
Распространенные сообщения об ошибках в Object variable or With block variable not set
Object variable or With block variable not set Проблемы, связанные с Windows Operating System:
- «Ошибка программного обеспечения Object variable or With block variable not set. «
- «Ошибка программного обеспечения Win32: Object variable or With block variable not set»
- «Извините, Object variable or With block variable not set столкнулся с проблемой. «
- «Object variable or With block variable not set не может быть найден. «
- «Отсутствует файл Object variable or With block variable not set.»
- «Ошибка запуска в приложении: Object variable or With block variable not set. «
- «Файл Object variable or With block variable not set не запущен.»
- «Отказ Object variable or With block variable not set.»
- «Object variable or With block variable not set: путь приложения является ошибкой. «
Ошибки Object variable or With block variable not set EXE возникают во время установки Windows Operating System, при запуске приложений, связанных с Object variable or With block variable not set (Windows Operating System), во время запуска или завершения работы или во время установки ОС Windows. При появлении ошибки Object variable or With block variable not set запишите вхождения для устранения неполадок Windows Operating System и чтобы HelpMicrosoft Corporation найти причину.
Источники проблем Object variable or With block variable not set
Эти проблемы Object variable or With block variable not set создаются отсутствующими или поврежденными файлами Object variable or With block variable not set, недопустимыми записями реестра Windows Operating System или вредоносным программным обеспечением.
Более конкретно, данные ошибки Object variable or With block variable not set могут быть вызваны следующими причинами:
- Поврежденные ключи реестра Windows, связанные с Object variable or With block variable not set / Windows Operating System.
- Вирус или вредоносное ПО, которые повредили файл Object variable or With block variable not set или связанные с Windows Operating System программные файлы.
- Другая программа (не связанная с Windows Operating System) удалила Object variable or With block variable not set злонамеренно или по ошибке.
- Другое приложение, конфликтующее с Object variable or With block variable not set или другими общими ссылками.
- Поврежденная загрузка или неполная установка программного обеспечения Windows Operating System.
Продукт Solvusoft
Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
yushkov Пользователь Сообщений: 11 |
#1 27.02.2019 12:07:32 Здравствуйте! Проблема: если в файле на любом листе внести какие-либо изменения (добавить текст в ячейку) или же просто открыть и закрыть ячейку без внесения изменений, то при последующем запуске макроса появляется ошибка Run-time error ’91 Object variable or With block variable not set’ (ошибка появляется в строке Loop While iFoundRng.Address <> firstAddress). До этого макрос работает нормально.
Прикрепленные файлы
|
||
skais675 Пользователь Сообщений: 2163 |
У меня работает отлично! Лучше выложите рядом и нерабочий пример. Изменено: skais675 — 27.02.2019 12:14:49 |
yushkov Пользователь Сообщений: 11 |
Дак я и приложил тот файл, в котором возникает ошибка. Попробовал запускать данный макрос на компьютерах коллег — у них всё работает хорошо, без ошибок. Значит, я так полагаю, проблема не в макросе, а в Excel на моем компе. Но что вызывает такую ошибку, может кто-нибудь знает? |
_Igor_61 Пользователь Сообщений: 3007 |
yushkov, добрый вечер! Довольно часто подобные вопросы возникают. Я не профи в компьютерной сфере, но исходя их опыта обычного пользователя уже давно сделал для себя вывод (это только ИМХО): вопрос скорее философский, нежели технический. Первое стандартное средство — переустановка программы (и хорошо, что в большинстве случаев помогает). Но почему она раньше работала отлично, а потом вдруг начинает косячить? Есть куча объяснений, но далеко не всегда они объясняют всё и вся. Возможно, изготовители железа и разработчики программ используют только экспериментальный опыт, а он не во всех ситуациях оказывается верным. Т.е. знаем: если сделать то-то и то-то, получается такой-то результат. (сравнение: если потереть ладони — почувствуешь, что они нагрелись). А вот почему так получается? Пока не будет знания об этом «почему», будут возникать и подобные вопросы. Живую клетку еще никому не удалось создать из ничего, возможно и тут что-то подобное. Возможно, камень не такой попался, не так на команды реагирует… повторюсь: ИМХО |
Alec Perle Пользователь Сообщений: 172 |
#5 27.02.2019 21:11:55 А что при ошибке содержится в переменной iFoundRng?
В Вашем случае проблемную строку нужно заменить на
|
||||
yushkov Пользователь Сообщений: 11 |
Alec Perle
, при ошибке iFoundRng = Nothing. Ещё заметил такую особенность: если внести изменения в какую-нибудь ячейку, сохраниться, закрыть файл, а потом снова открыть файл — то макрос работает без ошибок. Изменено: yushkov — 28.02.2019 06:33:03 |
Казанский Пользователь Сообщений: 8839 |
#7 28.02.2019 09:42:14
Пример плохой, он вызывает ошибку 91, можете убедиться.
Изменено: Казанский — 28.02.2019 09:44:52 |
||||
yushkov Пользователь Сообщений: 11 |
Казанский
, изменил код как Вы предложили — ошибка 91 перестала выскакивать. Спасибо. Но теперь возникла другая проблема: |
БМВ Модератор Сообщений: 20940 Excel 2013, 2016 |
yushkov, просто для эксперимента попробуйте этот файл, там почти ничего не изменялось По вопросам из тем форума, личку не читаю. |
yushkov Пользователь Сообщений: 11 |
БМВ
, попробовал Ваш файл. |
БМВ Модератор Сообщений: 20940 Excel 2013, 2016 |
yushkov, все ведет к тому что проблема в конкретном экземпляре ПК. Я так понимаю, что никто не смог воспроизвести ошибку. Я б рекомендовал для начала проверку памяти, потом полную перестановку , но только с чисткой . Изменено: БМВ — 01.03.2019 07:45:14 По вопросам из тем форума, личку не читаю. |
_Igor_61 Пользователь Сообщений: 3007 |
#12 01.03.2019 18:37:10 Только что наткнулся на интересную статью , возможно это о том, о чем в #4 |
Overview
VBA run-time error 91 is a common trappable error seen in VBA development. This error is triggered when you try to use an object variable (i.e. a variable which is of the “Object” type) that has no object (properly) assigned to it.
This error is a very common technical error which can often be encountered by beginners and even experienced programmers. Therefore, it is useful that you understand it, learn about how it is triggered, and how to work around it. This knowledge will help you in your development as a programmer in Microsoft Office.
Key Concept Before We Start — Value Assignment to Variables in VBA
Before we look into the topic of Error 91, let’s go through a very important coding concept in VBA about value assignment to variables. There are two main types of value assignment, which you can think of as (1) “object” and (2) “non-object”. You can see in the table below that for all variables which are non-objects, we simply use “=
” to assign values to them. However, for object variables, we must always begin the assignment with “Set“.
Variable Type | Scope | VBA syntax / treatment |
Normal (Non-Objects) | Any variable type that is not an object, e.g. integer, long, string, variate, etc. | Syntax: Set MyVariable = YourValue Example: Dim x As Integer x = 123 |
Objects | All variables which are objects. e.g. range, application, collection, etc. | Syntax: Set MyObject = YourObject
Example 1: |
You can now see why Error 91 is called “Object variable not Set”. It is because you should assign an object to an object variable with the SET statement.
So How is Error 91 Triggered?
There are four main reasons you might encounter this error:
- “Set” is omitted in the assignment of an object variable
- Using GoTo to jump into a “With” block
- Attempting to use an object variable that has been set to Nothing.
- Attempting to use an object which is not yet being created
Scenario 1: “Set” is Omitted in the Reference to an Object Variable
The macro “example1” below shows the most straightforward scenario when Error 91 can be triggered. The variable “MyObject
” is an object variable. In line 4, “MyObject = ActiveSheet
” attempts to assign a worksheet object (the ActiveSheet) to MyObject
. Because the SET
statement was omitted, this line of code causes Error 91 during run time.
Sub example1() Dim MyObject As Object 'Create object variable Dim x As String MyObject = ActiveSheet 'Create object reference [Err 91 here] x = MyObject.Name 'Assign Count value to x MsgBox "Sheet name is: " &amp;amp;amp; x End Sub
Solution:
To avoid making this mistake, you must always remember to use a Set statement to assign an object to an object variable.
See the correct way of object variable assignment with a Set statement in line 4 below:
Sub example1_fixed() Dim MyObject As Object 'Create object variable Dim x As String Set MyObject = ActiveSheet 'Create object reference the correct way x = MyObject.Name 'Assign Count value to x MsgBox "Sheet name is: " &amp;amp;amp; x End Sub
Scenario 2: Using GoTo to Jump into a “With” Block
If a GoTo statement jumps into a With block, it may cause Error 91. See the example below:
Sub BadJumper() Dim x As Integer 'counter for use with for loop Dim result As String x = WorksheetFunction.RandBetween(1, 10) 'Draw integer between 1&amp;amp;amp;10 If x &amp;amp;gt; 5 Then GoTo jumper1 'Jump if x &amp;amp;gt;5 Else End 'Terminate macro if x&amp;amp;lt;=5 End If With Range("A1") jumper1: .Value = x 'place rolling total [Err 91 here] End With End Sub
In line 6, the GoTo statement jumps to “jumper1” when x>5. The With statement in line 10 is bypassed and the process jumps straight to line 12 which is supposed to put the value of x into cell A1. Error 91 will be trigger right there.
Having the With statement (line 10) bypassed, Excel has no idea what object the “Value” property (line 12) refers to, and therefore has no idea where to place the value of x.
Solution:
To avoid this mistake, make sure your GoTo statements never jump directly inside a WITH block.
Scenario 3: Attempting to Use an Object Variable that Has Been Set to Nothing.
Error 91 can also be triggered when the code attempts to use an object variable that has been set to “Nothing”. (i.e. the object variable has been reset/erased.)
In line 5 of the macro below, the object variable “MyObject
” has been reset by the statement “Set MyObject = Nothing
“. Error 91 will happen in line 6 (when the code tries to display the name of MyObject in a Msgbox). This is equivalent to having an blank object variable which has nothing assigned to it.
Sub example3() Dim MyObject As Object 'Create object variable. Set MyObject = ActiveSheet 'Create valid object reference. MsgBox "Sheet name is: " &amp;amp;amp; MyObject.Name Set MyObject = Nothing MsgBox "Sheet name is: " &amp;amp;amp; MyObject.Name '[Err 91 here] End Sub
Solution:
After resetting an object variable by setting it to nothing, make sure you re-assign an object to it (with a Set
statement) before calling it.
Scenario 4: Attempting to Use an Object which Is Not Yet Created During Run-Time
The previous examples showed Error 91 scenarios in which objects have not been properly assigned to object variables. There are situations where Error 91 is triggered because the object has not been created.
This scenario normally applies to objects which are not under any of the Microsoft Office Application objects. For instance, (1) generic Visual Basic objects (such as Collection, Dictionary) or (2) Objects in libraries added through “Add Reference”.
Example (part 1):
The two macros below “ex4_Collection
” and “ex4_Dictionary
” contain very typical mistakes made by VBA programmers when using Collections and Dictionaries. In line 2 of both macros, the objects were declared, and then values are being added to the Collection/Dictionary in line 3, where Error 91 occurred.
Sub ex4_Collection() Dim MyCollection1 As Collection MyCollection1.Add Item:=123 '[Err 91 here] End Sub
Sub ex4_Dictionary() Dim dict As Scripting.Dictionary dict.Add "key1", 123 '[Err 91 here] End Sub
Solution:
To fix the macro, you need to learn the syntax to create a new instance of the object. See below how the two macros are fixed by inserted a new Set statement in line 3 of both macros.
Sub ex4_Collection_fixed () Dim MyCollection1 As Collection Set MyCollection1 = New Collection 'create the Collection MyCollection1.Add Item:=123 End Sub
Sub ex4_Dictionary_fixed() Dim dict As Scripting.Dictionary Set dict = New Scripting.Dictionary 'create the Dictionary dict.Add "key1", 123 End Sub
Example (part 2):
Here is another very common case when a reference to a library is added. For example, the Office library is added through “Add Reference” from the Tools menu in VB Editor:
The macro below tries to create a Mail item. But Error 91 will be triggered in line 3. The macro seems perfectly fine, where the Outlook application object and the MailItem object have been declared, and then a Set statement is used to create a Mail item. But why there is still the Error 91?
Sub ex4_Outlook() Dim OutlookApp As Outlook.Application Dim OutlookMail As Outlook.MailItem Set OutlookMail = OutlookApp.CreateItem(olMailItem) End Sub
The macro below shows the correct approach to create such an (early binding) instance of the Outlook application object. See how line 3 has been added?
Sub ex4_Outlook_fixed() Dim OutlookApp As Outlook.Application Dim OutlookMail As Outlook.MailItem Set OutlookApp = New Outlook.Application 'create Outlook App Set OutlookMail = OutlookApp.CreateItem(olMailItem) End Sub
The skills to interact with object variables is crucial in VBA development and successful declaration and assignment are the first steps. Understanding the above scenarios can for sure help you program more efficiently in VBA.
Attention Before you read this post, I highly recommend you check out my resources page for access to the tools and services I use to not only maintain my system but also fix all my computer errors, by clicking here!
A runtime error is basically an error that occurs during a programs “runtime”, to put it simply. Each runtime error has its own error code, such as 91, in this case. When an individual experiences a runtime error 91 on their computer, it’s usually accompanied by a “Object variable set to nothing” error message.
Runtime error 91 is a fairly common error on Windows based systems that usually occur at random moments. This error doesn’t have a clear defined cause; however, the Visual Basic DCOMCnfg.exe on your computer is one known culprit for this error; which is usually the result of damage, and/or corruption to this file. With that said, there are a number of things that you can do, when you find yourself in this situation.
Symptoms of Runtime Error 91
There are a number of symptoms individuals may experience when they encounter an error 91, but of the various symptoms, the most common are the following:
- The active program window crashes, just as the Error 91 dialog box appears.
- Error 91 frequently crashes, as you attempt to run the same application.
- “Object variable or with block variable not set” error message is displayed.
- Windows performance becomes very slow and unresponsive to both keyboard and mouse input.
- Computer randomly freezes for several seconds at a time.
The runtime error 91 can occur while you are installing an application, while you are using a program, within a Windows based environment, during the startup phase of your computer or while it is shutting down, or even when installing Windows for the first time. Keeping note of when you actually experience this error is very important, as it will help you when troubleshooting the problem.
Cause of Error
Already speaking briefly about the cause of this error, .NET Framework and Visual Studio (in addition to DCOMCnfg.exe) are also known to be related to this error; these are tools used in the development of applications.
Within a programming environment, the runtime error 91 would tell the programmer that an invalid variable, which has the value of “nothing”, is being referenced to.
Usually, it’s not known whether or not an application will generate a runtime error 91, till after the user attempts to run it. Error 91 can also be caused by a network blackout, while an application is attempting to download additional data from its server.
The general consensus amongst this error is that it occurs, when attempting to use an application that has issues with the variables within it.
A variable is essentially a container that a programmer will use to store flexible data. An invalid variable could relate to the wrong kind of data being stored in a variable, or the variable being incorrectly referenced.
Fixing this error will thus, entail repairing the coding of a particular application, in order to prevent the error from reappearing, every time you try to use it.
Fixing Runtime Error 91
Below are a number of fixes that an individual can attempt when trying to fix this problem. This error is a pretty difficult one to fix, because of the personal nature of it, as it relates to the application. However, there are still many things that you can do, to at least mask the problem.
Use Registry Cleaner
One thing you should definitely do before anything else is use a registry cleaner to scan through your system so that it can repair any damaged configurations which could be aiding the runtime error.
The function of the registry cleaner is to fix errors within your computers registry, the registry is the area of the computer were all you’re most important data is stored, such as system options, preferences and various other things.
Whenever you install and use an application on your computer, numerous registry settings are created and used, but this process can also lead to redundant entries, invalid registry keys and damaged settings.
Fixing this problem will require you to use a registry cleaner, which will scan through your entire system, locate all of these errors and fix them. With that said, there are various registry cleaners out there, but the one I personally recommend is Advanced System Repair Pro, and that’s because of its multifaceted nature. Anyway, you can pick this tool up here:
CLICK HERE TO CHECK OUT ADVANCED SYSTEM REPAIR PRO
Check for Viruses
The next step you should consider doing when attempting to fix a runtime error 91, is to use an antivirus scanner. In a lot of situations, this issue is the result of malware or viruses running within the background of the computer causing the application to crash, every time you use it. Because viruses spread, infecting more components of your operating system over time, it’s very important that you address it as soon as possible.
A good antivirus program should have little difficulty finding the virus on your computer, and removing it. Antivirus tools are very easy to use, the only thing that is required on your end, is to ensure that everything on it is up-to-date, especially its virus definitions.
With that said, simply run a full scan of your system, for this task. If you don’t have an antivirus tool on your computer, or you think your tool isn’t very good, then I recommend you use SpyHunter, alternatively you could check out my post on the very best antivirus tools.
To learn more about SpyHunter, please visit the following link:
CLICK HERE TO CHECK OUT SPYHUNTER
Reinstall Application
If all other methods have failed, then you should consider reinstalling the application. There is a good chance that the error was due to an incomplete installation, in which case, a reinstallation should fix it.
When it comes to reinstalling the application, you want to ensure that every trace of the application is removed; this includes redundant files, folders and registry entries, before you reinstall it.
However, in order for you to do this, you will need to use the uninstallation tool called Express Uninstaller. This powerful removal tool is capable of not only removing applications using the conventional InstallShield, but also running independent scans of your operating system and registry and removing all associated data. Anyway, you can acquire this excellent tool from here:
CLICK HERE TO CHECK OUT EXPRESS UNINSTALLER
Check for Patches
Whenever an individual encounters a runtime error 91 while attempting to run a program, there is very little they can do about the coding for that particular program. However, one possibility entails checking the website of the developer, to see whether or not they have released a patch that fixes the bug in the code.
If you do find a patch, simply download it, and apply it to the program. The patch should come with its own update facility to make the update process more seamless.
Alternatively, if the program has its own update utility, you can try that, before heading off to the website of the developer.
Check Windows Updates
Another idea that has proven to be quite effective at fixing this problem involves checking for Windows updates. This is because, not only do developers release patches for bugs in their programs, but so does Microsoft, for their operating system.
If the application that is generating a runtime error 91 came preinstalled with your computer, when you purchased it, then you can try checking the websites of the computer manufacturers for any updates for this problem.
This is an excellent way for you to find all the appropriate updates for your computer make and model. You may find updates that fix the runtime error in additional to updates that may improve the overall performance of your computer. By keeping your computer up-to-date with the latest updates, not only will it secure it from bugs, but it will also secure it from hacks and viruses.
Configure DCOMCnfg.exe
If the runtime error you’re experiencing is due to the DCOMCnfg.exe, then you will need to reconfigure its settings to fix the problem. The purpose of this program is to control file permissions and various other things, related to Visual Basic, on your computer.
Unfortunately, if the necessary steps are not taken to rectify this problem, the error will persist, thus it’s important that you configure DCOMCnfg.exe to Allow “Everyone”.
If you don’t know how to do this, I suggest you check out the following report: https://support.microsoft.com/en-us/kb/183607
Turn Off Error Messages
If you’ve searched for a fix for the application, but were unable to find anything, then the first thing you should do is contact the developer to notify them about the problem.
The next option available to you is to turn off script debugging, that way, you won’t have to see the error message, every time it occurs. After all, the error message is of little value to you.
The Machine Debug Manager is the tool that operates the script debugging, a tool that you can control through Internet Explorer. Anyway, to disable it, simple do the following:
1. First, ensure you have booted into your computer with administrative rights.
2. Then, double click on the Internet Explorer Icon, to start the browser.
3. Once Internet Explorer starts, click on Tools [Cog] -> Internet Options.
4. This will bring up the Internet Options, from here, click on the Advanced Tab, and check the box next to Disable Script Debugging (Internet Explorer) and Disable Script Debugging (Other) then click on OK.
Are you looking for a way to repair all the errors on your computer?
If the answer is Yes, then I highly recommend you check out Advanced System Repair Pro.
Which is the leading registry cleaner program online that is able to cure your system from a number of different ailments such as Windows Installer Errors, Runtime Errors, Malicious Software, Spyware, System Freezing, Active Malware, Blue Screen of Death Errors, Rundll Errors, Slow Erratic Computer Performance, ActiveX Errors and much more. Click here to check it out NOW!
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
Sub SAVE_CHANGES() Dim CurADNumber As String Dim RezPoiskaAD As Range Dim FindedRow As Long CurADNumber = Me.TextBox_AD_CN_No.Value If CurADNumber <> "" Then With ThisWorkbook.Worksheets("AD_EVALUATION_STATUS") .Unprotect Password:="123" Set RezPoiskaAD = .Columns(1).Find(What:=CurADNumber, LookIn:=xlFormulas, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not RezPoiskaAD Is Nothing Then FindedRow = RezPoiskaAD.Row .Cells(FindedRow, .Rows(2).Find("AMENDMENT").Column) = Me.TextBox_AMENDMENT.Value .Cells(FindedRow, .Rows(2).Find("EFFECTIVE DATE").Column) = CDate(Me.TextBox_EFFECTIVE_DATE) .Cells(FindedRow, .Rows(2).Find("SUPERSEDES").Column) = Me.TextBox_SUPERSEDES.Value .Cells(FindedRow, .Rows(2).Find("SUBJECT").Column) = Me.TextBox_SUBJECT.Value If Me.OptionButton_ONE_TIME.Value = True Then .Cells(FindedRow, .Rows(2).Find("ONE TIME").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("ONE TIME").Column) = "" End If If Me.OptionButton_REPETITIVE.Value = True Then .Cells(FindedRow, .Rows(2).Find("REPETETIVE").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("REPETETIVE").Column) = "" End If If Me.OptionButton_OPTIONAL.Value = True Then .Cells(FindedRow, .Rows(2).Find("OPTIONAL").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("OPTIONAL").Column) = "" End If If Me.CheckBox_AIRFRAME.Value = True Then .Cells(FindedRow, .Rows(2).Find("AIRFRAME").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("AIRFRAME").Column) = "" End If If Me.CheckBox_APPLIANCE.Value = True Then .Cells(FindedRow, .Rows(2).Find("APPLIANCE").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("APPLIANCE").Column) = "" End If If Me.CheckBox_ENGINE.Value = True Then .Cells(FindedRow, .Rows(2).Find("ENGINE").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("ENGINE").Column) = "" End If .Cells(FindedRow, .Rows(2).Find("REMARKS").Column) = Me.TextBox_APPLICABILITY_REMARKS.Value .Cells(FindedRow, .Rows(2).Find("REFERENCES").Column) = Me.TextBox_REFERENCE.Value .Cells(FindedRow, .Rows(2).Find("THRESHOLD").Column) = Me.TextBox_THRESHOLD.Value .Cells(FindedRow, .Rows(2).Find("DEADLINE").Column) = Me.TextBox_DEADLINE.Value .Cells(FindedRow, .Rows(2).Find("INTERVAL").Column) = Me.TextBox_INTERVAL.Value .Cells(FindedRow, .Rows(2).Find("EO REF").Column) = Me.TextBox_EO_REF.Value .Cells(FindedRow, .Rows(2).Find("TASK CARD").Column) = Me.TextBox_TASK_CARD.Value If Me.CheckBox_0157.Value = True Then .Cells(FindedRow, .Rows(2).Find("0157").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("0157").Column) = "" End If If Me.CheckBox_0277.Value = True Then .Cells(FindedRow, .Rows(2).Find("0277").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("0277").Column) = "" End If If Me.CheckBox_0292.Value = True Then .Cells(FindedRow, .Rows(2).Find("0292").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("0292").Column) = "" End If If Me.CheckBox_24837.Value = True Then .Cells(FindedRow, .Rows(2).Find("24837").Column) = "X" Else .Cells(FindedRow, .Rows(2).Find("24837").Column) = "" End If .Cells(FindedRow, .Rows(2).Find("DESCRIPTION").Column) = Me.TextBox_DESCRIPTION.Value .Cells(FindedRow, .Rows(2).Find("EVALUATED BY Name").Column) = Me.TextBox_EVALUATED_BY_NAME.Value .Cells(FindedRow, .Rows(2).Find("EVALUATED BY Date").Column) = Me.TextBox_EVALUATED_BY_DATE.Value .Cells(FindedRow, .Rows(2).Find("DUPLICATED EVALUATION Name").Column) = Me.TextBox_DUPLICATED_BY_NAME.Value .Cells(FindedRow, .Rows(2).Find("DUPLICATED EVALUATION Date").Column) = Me.TextBox_DUPLICATED_BY_DATE.Value End If .Protect Password:="123" End With Else MsgBox "(AD/CN No) field is empty, please fill it before save" End If End Sub |