Microsoft visual basic runtime error 424

Object required (Error 424) References to properties and methods often require an explicit object qualifier. This error has the following causes and solutions: You referred to an object property or method, but didn’t provide a valid object qualifier. Specify an object qualifier if you didn’t provide one. For example, although you can omit an […]

Содержание

  1. Object required (Error 424)
  2. Support and feedback
  3. Требуется объект (ошибка 424)
  4. Поддержка и обратная связь
  5. Runtime Error 424 “Object Required” Error Fix Tutorial for Windows 7/8/10
  6. The error is caused by Excel not having access to a data “object” referenced in the code. This may be a variable, class or library reference…
  7. ➡️ Explanation
  8. 💾 Overview
  9. 🖥️ ️Cause
  10. 🔌 Solution
  11. 1️⃣ Code Combing
  12. 2️⃣ Debug
  13. ☎️ Further Support ☎️
  14. 📥 Thanks For Reading! 📥
  15. Name already in use
  16. VBA-Docs / Language / Reference / User-Interface-Help / object-required-error-424.md
  17. Microsoft visual basic runtime error 424 object required
  18. Answered by:
  19. Question
  20. Answers

Object required (Error 424)

References to properties and methods often require an explicit object qualifier. This error has the following causes and solutions:

You referred to an object property or method, but didn’t provide a valid object qualifier. Specify an object qualifier if you didn’t provide one. For example, although you can omit an object qualifier when referencing a form property from within the form’s own module, you must explicitly specify the qualifier when referencing the property from a standard module.

You supplied an object qualifier, but it isn’t recognized as an object. Check the spelling of the object qualifier and make sure the object is visible in the part of the program in which you are referencing it. In the case of Collection objects, check any occurrences of the Add method to be sure the syntax and spelling of all the elements are correct.

You supplied a valid object qualifier, but some other portion of the call contained an error. An incorrect path as an argument to a host application’s File Open command could cause the error. Check arguments.

You didn’t use the Set statement in assigning an object reference. If you assign the return value of a CreateObject call to a Variant variable, an error doesn’t necessarily occur if the Set statement is omitted. In the following code example, an implicit instance of Microsoft Excel is created, and its default property (the string «Microsoft Excel») is returned and assigned to the Variant RetVal . A subsequent attempt to use RetVal as an object reference causes this error:

Use the Set statement when assigning an object reference.

In rare cases, this error occurs when you have a valid object but are attempting to perform an invalid action on the object. For example, you may receive this error if you try to assign a value to a read-only property. Check the object’s documentation and make sure the action you are trying to perform is valid.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Требуется объект (ошибка 424)

Для ссылок на свойства и методы зачастую требуется явный описатель объекта. Эта ошибка имеет следующие причины и решения:

При ссылке на свойство или метод объекта не указан допустимый описатель объекта. Укажите описатель объекта, если он не задан. Например, можно опустить описатель объекта при ссылке на свойство формы в собственном модуле формы, однако, необходимо явно задать описатель при ссылке на свойство из стандартного модуля.

Описатель объекта указан, но не распознается как объект. Проверьте правильность написания описателя объекта и убедитесь в том, что объект видим в той части программы, где на него присутствует ссылка. В случае с объектами коллекции проверьте все вхождения метода Add, чтобы убедиться в том, что для всех элементов используется правильный синтаксис и правописание.

Указан допустимый описатель объекта, но другие части вызова содержат ошибку. Некорректный путь в качестве аргумента для команды Open File Open для хост-приложения может привести к ошибке. Проверьте аргументы.

При назначении ссылки на объект не использовался оператор Set. Если при назначении возвращаемого значения вызова CreateObject в переменную Variant пропущен оператор Set, ошибка может не возникать. В следующем примере кода создается неявный экземпляр Microsoft Excel, а его свойство по умолчанию (строка «Microsoft Excel») возвращается и назначено варианту RetVal . Последующая попытка использования в RetVal качестве ссылки на объект вызывает эту ошибку:

Используйте оператор Set при назначении ссылки на объект.

В редких случаях эта ошибка возникает при попытке выполнить недопустимое действие в отношении допустимого объекта. Например, ошибка может произойти при попытке присвоить значение свойству «только чтение». Просмотрите документацию по объекту и убедитесь в том, что вы пытаетесь выполнить допустимое действие.

Для получения дополнительной информации выберите необходимый элемент и нажмите клавишу F1 (для Windows) или HELP (для Macintosh).

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Runtime Error 424 “Object Required” Error Fix Tutorial for Windows 7/8/10

The error is caused by Excel not having access to a data “object” referenced in the code. This may be a variable, class or library reference…

The “ Runtime Error 424 (Object Required)” error is caused by Excel being unable to access to an “object” referenced in your VBA code:

The error is caused by a function being called on a reference you’ve either misspelled, or have not declared.

The solution is to ensure you have all the appropriate references declared within your code. The simplest ways to fix the problem is as follows:

  • Locate the offending line of code (if not highlighted, use debug mode)
  • Identify whether you’ve referenced any objects which aren’t declared
  • Look for any of the functions which may be causing an error and identify they are called correctly (with the correct syntax)
  • Remove as much code as possible in order to get the application working again, and then add back the lines one-by-one (this isolates the error and allows yo to fix any of the issues it may have)

➡️ Explanation

You need to understand that all computer programs are long lines of code.

These lines contain instructions which the computer will process,
performing functions that will interact with a variety of different objects within the system.

Whenever you use the likes of VBA, you need to appreciate that in order for the computer to process the various functions you’re calling in your script, anything referenced by the script has to be loaded prior to it being read.

The problem you have is that you’re trying to call an object, which has either not been referenced properly, or is not loaded into the system. The result is your application will fail, and you’ll be presented with a multitude of potential errors.

💾 Overview

“VBA” (Visual Basic for Applications) is used to create event-based functionality (using the “Visual Basic” language) inside the likes of Excel, Word, Powerpoint and other software.

Introduced in 1993, VBA forms a core part of Microsoft’s “Office” suite → enabling people to add programmatic functionality to their documents, spreadsheets and presentations…

Whilst effective, because it is (at its core) a programming environment, it’s easy to succumb to problems if you’re not experienced.

This lies at the core of what causes the Runtime 424 (Object Required) error → people referencing “objects” which don’t exist or are not loaded by Excel.

🖥️ ️Cause

“Runtime” errors are a common problem for many desktop applications; purveyors of Windows (pre-10) will be very familiar with them…

Runtime errors have been a problem for a long time

Whilst these errors show for many reasons, they have the same cause → something in a software’s source code prevented it from running …

To appreciate why this is a problem, you must understand that all computer programs are essentially a “list” of commands which are held in memory by the computer…

These commands are stored in 3 “layers”:

  1. GUI layer(shows the user a series of inputs)
  2. Application layer (stores the “business logic” for the application)
  3. Database layer (storing all of the functions, methods, variables and data required to keep the application running).

The way an application works is to load all of these commands into memory, and provides users with the ability to interact with them via a GUI.

Whereas there are many reasons why this process may fail, one of the most common (and why “Runtime” errors exist) is that the functions inside these commands may reference a script or object that doesn’t exist…

This causes the application to “fail”, and Windows (or whichever OS you’re running) will have to show an error, describing what went wrong.

In terms of your VBA environment, the problem is due to a reference you made to a Worksheet, object, variable or file, which Excel has not loaded.

This is relatively simple to resolve, but requires understanding.

🔌 Solution

The core solution to “ Runtime Error 424” is to locate any references you have in your VBA code which are not present within Excel…

The simplest way to do this is to comb through each line of code and
remove any issues which may be in there.

There is an easy way to do this, and it works very well to fix the majority of Runtime 424 errors in VBA:

  1. The first — and most effective — solution is to manually comb through the code. This involves removing blocks of code in order to try and get it running, adding the system. This helps you identify the offending line, allowing for more specific inspection.
  2. The second — and more methodical — method is to use the “Code Stepping” feature of VBA. This can be done using F8 within the VBA development environment…

1️⃣ Code Combing

The first step is to comb through your application’s code.

Doing this is simple. You need to remove any of the code which may be causing a problem, and gradually add it back again.

2️⃣ Debug

The second method is to let VBA “walk” through your code, removing any element which may be causing issues.

To do this, we can utilize the “code stepping” feature, which allows us to visualize how each line of code is running:

In order to do this, you need to ensure you’re in the VBA editor.

This is done by clicking on the “Visual Basic” button inside Excel:

To get to this, you need to click on File → Options → Customize Ribbon, and ensure that “Developer” is checked.

This will create the “Developer” tab at the top of the screen, and allow you to click onto the likes of “ Visual Basic” and other buttons as a result.

Once you click on this button, you’ll be presented with a

☎️ Further Support ☎️

If you need further support, please feel free to contact → we’re a UK software company who specialize in support & scalability.


We have a 👾 PCFixes.com 👾 support page if you require further help.

You’re also welcome to talk to us through the page below ↴

🎧 Live support 🎧 is STRONGLY recommend IF you use your system for business or work.

If you need the help right now, getting an expert on screen gives you the ability to at least get a second opinion (and perhaps someone to help guide you through the fix). Live support is the only way to do this.

⚠️ Do NOT use live services that charge up front. ONLY use companies who provide live support without ANY up-front commitments…⚠️

✔️ PCFixes.com is the only recognized online system repair service
✔️ PCFixes.com is operated from the UK by veteran PC repair technicians
✔️ PCFixes.com gives 24/7 support to anyone needing system repairs

📥 Thanks For Reading! 📥

If you need further help, please feel free to ask below…

Источник

Name already in use

VBA-Docs / Language / Reference / User-Interface-Help / object-required-error-424.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

Copy raw contents

Copy raw contents

Object required (Error 424)

References to properties and methods often require an explicit object qualifier. This error has the following causes and solutions:

You referred to an object property or method, but didn’t provide a valid object qualifier. Specify an object qualifier if you didn’t provide one. For example, although you can omit an object qualifier when referencing a form property from within the form’s own module, you must explicitly specify the qualifier when referencing the property from a standard module.

You supplied an object qualifier, but it isn’t recognized as an object. Check the spelling of the object qualifier and make sure the object is visible in the part of the program in which you are referencing it. In the case of Collection objects, check any occurrences of the Add method to be sure the syntax and spelling of all the elements are correct.

You supplied a valid object qualifier, but some other portion of the call contained an error. An incorrect path as an argument to a host application’s File Open command could cause the error. Check arguments.

You didn’t use the Set statement in assigning an object reference. If you assign the return value of a CreateObject call to a Variant variable, an error doesn’t necessarily occur if the Set statement is omitted. In the following code example, an implicit instance of Microsoft Excel is created, and its default property (the string «Microsoft Excel») is returned and assigned to the Variant RetVal . A subsequent attempt to use RetVal as an object reference causes this error:

Use the Set statement when assigning an object reference.

In rare cases, this error occurs when you have a valid object but are attempting to perform an invalid action on the object. For example, you may receive this error if you try to assign a value to a read-only property. Check the object’s documentation and make sure the action you are trying to perform is valid.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

Источник

Microsoft visual basic runtime error 424 object required

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I do not understand why I am receiving the above run-time error. i must be violating a basic

principle of VBA (2003)

When I look at the workbook immediately after I receive the run-time error I see a copy of the desired worksheet placed exactly where it should be, but the code never ran far enough to rename the worksheet.

Dim aworkbook As Workbook
Dim newWorksheet As Worksheet

MsgBox («Workbooks(1) =» & Workbooks(1).Name) ‘ confirm correct workbook exists
With Workbooks(«AWorkbook.xls»)
Set newWorksheet = .Worksheets(«Aworksheet»).Copy( _
After:=.Worksheets(«aworksheet»))

‘ ERROR OCCURS AFTER EXECUTING THE ABOVE LINE OF CODE
newWorksheet.Name = «Inverted Aworksheet»
End With

‘ code that inverts data within newWorksheet

Answers

not sure how to handle it exactly like you are attempting but this will do the trick in a few steps

the idea is to use something we know is consistent. sheets(1) will always be the first sheet in the list so we can just set the newly copied sheet before the first sheet, which now makes the copied sheet the new first sheet. then we can get the copied sheet (aka the first sheet) and move it after the original sheet that was copied.

Источник

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Object required (Error 424)

vblr6.chm1000424

vblr6.chm1000424

office

282292d7-d147-b71e-4d1e-149af7da8f7e

06/08/2017

medium

References to properties and methods often require an explicit object qualifier. This error has the following causes and solutions:

  • You referred to an object property or method, but didn’t provide a valid object qualifier. Specify an object qualifier if you didn’t provide one. For example, although you can omit an object qualifier when referencing a form property from within the form’s own module, you must explicitly specify the qualifier when referencing the property from a standard module.

  • You supplied an object qualifier, but it isn’t recognized as an object. Check the spelling of the object qualifier and make sure the object is visible in the part of the program in which you are referencing it. In the case of Collection objects, check any occurrences of the Add method to be sure the syntax and spelling of all the elements are correct.

  • You supplied a valid object qualifier, but some other portion of the call contained an error. An incorrect path as an argument to a host application’s File Open command could cause the error. Check arguments.

  • You didn’t use the Set statement in assigning an object reference. If you assign the return value of a CreateObject call to a Variant variable, an error doesn’t necessarily occur if the Set statement is omitted. In the following code example, an implicit instance of Microsoft Excel is created, and its default property (the string «Microsoft Excel») is returned and assigned to the Variant RetVal. A subsequent attempt to use RetVal as an object reference causes this error:

      Dim RetVal ' Implicitly a Variant. 
      ' Default property is assigned to Type 8 Variant RetVal. 
      RetVal = CreateObject("Excel.Application") 
      RetVal.Visible = True ' Error occurs here. 

    Use the Set statement when assigning an object reference.

  • In rare cases, this error occurs when you have a valid object but are attempting to perform an invalid action on the object. For example, you may receive this error if you try to assign a value to a read-only property. Check the object’s documentation and make sure the action you are trying to perform is valid.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

[!includeSupport and feedback]

Home / VBA / VBA Object Required Error (Error 424)

When VBA is not able to recognize the object for which you are referring to the property or a method it shows you the Object Required error. In simple words, if you refer to an object, but the name of that object is not correct (that object is not in the VBA’s object hierarchy) it shows error 424, like the following.

In the above code, as you can see, I have misspelled the active cell object, and when VBA’s executes that line of code can’t that object because there’s no object with that name (as I have misspelled it).

Note: If you have used the Option Explicit statement in the module then with the same, you’ll get a different error (see image below).

Used “Set” Keyword for a Non-Object Variable

When you use a variable to assign an object to it, you need to use the keyword “Set”. In the following example, you have a myWKS for the worksheet and iVal for the value from cell A1.

As you can see, in the above code you have variables out of which one is declared as a worksheet object and the second as a string. But at the time of assigning the value, we have used the “Set” keyword to the variable “iVal” which is not declared as an object but as a string.

How to Fix Object Required (Error 424) in VBA

  1. Go to the Debug menu in your visual basic editor.
  2. Use the step to run the entire code step by step.
  3. The moment you reach the line where you have an error VBA will show you an error.
  4. Correct that line of code.

The other way could be going through the code line by line by reading it to make sure you are referring to the right objects and using the correct name of the variables and objects.

You can also use the GOTO statement to surpass an error or show a message to the users once an error occurred.

More on VBA Errors

Subscript Out of Range (Error 9) | Type Mismatch (Error 13) | Runtime (Error 1004) | Out of Memory (Error 7) | Object Doesn’t Support this Property or Method (Error 438) | Invalid Procedure Call Or Argument (Error 5) | Overflow (Error 6) | Automation error (Error 440) | VBA Error 400

  • Remove From My Forums
  • Question

  • I do not understand why I am receiving the above run-time error. i must be violating a basic

    principle of VBA (2003)

    When I look at the workbook immediately after I receive the run-time error I see a copy of the desired worksheet placed exactly where it should be, but the code never ran far enough to rename the worksheet.

    Sub invert()

            
        Dim aworkbook As Workbook
        Dim newWorksheet As Worksheet

        
        MsgBox («Workbooks(1) =» & Workbooks(1).Name)  ‘ confirm correct workbook exists
        With Workbooks(«AWorkbook.xls»)
            Set newWorksheet = .Worksheets(«Aworksheet»).Copy( _
            After:=.Worksheets(«aworksheet»))

    ‘ ERROR OCCURS AFTER EXECUTING THE ABOVE LINE OF CODE
            newWorksheet.Name = «Inverted Aworksheet»
        End With

    ‘ code that inverts data within newWorksheet

    end sub

    please help me.

    Thank you

    Bil

Answers

  • Bill,

    not sure how to handle it exactly like you are attempting but this will do the trick in a few steps

     Dim CurWorkbook As Workbook: Set CurWorkbook = Workbooks("Book1")
     Dim newWorksheet As Worksheet
     With CurWorkbook
     .Sheets("Sheet1").Copy Before:=.Sheets(1)
     Set newWorksheet = .Sheets(1)
     newWorksheet.Name = "test"
     .Sheets("test").Move After:=.Sheets("Sheet1")
     End With

    the idea is to use something we know is consistent.  sheets(1) will always be the first sheet in the list so we can just set the newly copied sheet before the first sheet, which now makes the copied sheet the new first sheet.  then we
    can get the copied sheet (aka the first sheet) and move it after the original sheet that was copied.

    hope that makes sense.  I am sure there is a way to do it similar to how you are attempting, and i have seen something similar with worksheets.add, but did not come across any examples to set a new sheet object as a copy all in one statement. 
    not sure about that one, as i got the same error trying a few things close to yours.

    hope this helps


    • Marked as answer by

      Wednesday, May 5, 2010 7:25 AM

Ошибка 424 буквально означает следующее: «требуется объект» или «заблокировано правилами безопасности сайта». Возникает при атаке на сайт популярных CMS, ввиду множественных параллельных запросов или обращение к объекту с ошибкой.

Множественные запросы

Данная ошибка указывает на то, что для выполнения запроса со стороны пользователя должна завершиться еще одна или несколько параллельных операций. В случае, если происходит сбой в одном из процессов, то потеряется все соединение сразу. Таким образом, дальнейшая обработка всего запроса становится невозможной. Подобное может происходить, если некорректно был завершен один из предыдущих процессов. Не путайте данную ошибку с ошибкой 403, когда вам просто запрещен доступ к информации.

Решение проблемы

Завершите параллельные запроса или остановите выполнение команд. В случае, если вы не находите, что именно нужно остановить — проверьте логи. Каждый случай индивидуален, т.к. чаще всего ошибка 424 возникает по другим причинам. Если у вас конкретно эта причина — напишите в комментариях проблему и приложите скриншот. Наш администратор разберёт вопрос в течении 24-х часов.

Правила безопасности CMS сайта

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

Решение проблемы

Нет повода для беспокойств, т.к. в этом случае просто сработал защитный механизм от сканирования уязвимостей сайта. Часто с этим сталкиваются пользователи популярных CMS. Для предотвращения взлома рекомендуем проверить логи сайта, найти ip от которого идут запросы и отправить его в блок лист.

Если ошибка 424 возникает на веб-странице, то можно выключить данную опцию. Необходимо перейти в Панель управления — Хостинг — Мои сайты — Логи и нажать на «Error» для просмотра списка (путь может отличаться в зависимости от хостинга). В новом окне нужно начать поиск записи, отображающей запрос. В появившейся строчке выбрать «Выключить правило», и в течение получаса опция отключится.

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

Требуемый объект возвращает ошибку

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

Сбой возникает, если при попытке вызвать объект, который либо не правильно указан, либо не был загружен в систему. В результате ваше приложение выйдет из строя, и вы увидите множество потенциальных ошибок.

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

Решение ошибки

Решение проблемы состоит в том, чтобы проверить, что в вашем коде указаны все соответствующие ссылки.

«VBA» (Visual Basic для приложений) используется для создания функциональных возможностей на основе событий (с использованием языка «Visual Basic») в Excel, Word, Powerpoint и других программах. Представленный в 1993 году, VBA является основной частью пакета Microsoft Office.

Ошибки «времени выполнения» — распространенная проблема для многих настольных приложений. Ошибки времени выполнения были проблемой в течение долгого времени.

Они хранятся в трех «слоях»:

  1. Слой графического интерфейса пользователя (показывает пользователю серию входных данных)
  2. Уровень приложения (хранит «бизнес-логику» приложения)
  3. Уровень базы данных (хранящий все функции, методы, переменные и данные, необходимые для работы приложения).

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

Ваши действия:

  1. При обращении к свойству или методу объекта укажите нужный описатель объекта. Следует его указать, если он не задан.
  2. Допущена ошибка в написании объекта, поэтому не происходит его распознавания. Следует убедиться в правописании той части программы, где присутствует ссылка на объект.
  3. Правильность написания соблюдена, но стоит пересмотреть другие элементы ссылки, которые содержат ошибки. Необходимо проверить аргументы.
  4. Если пользователь собирается совершить недопустимую операцию к допустимому объекту. Пример: сбой происходит при попытке присвоить значение свойству «только чтение». Решение: проверить документацию по файлу и убедиться в том, что действие допустимо.

Ошибка  424 и Visual Basic

Одна из наиболее распространенных (и почему существуют ошибки «времени выполнения») заключается в том, что функции внутри этих команд могут ссылаться на скрипт или объект, которых не существует.

Ошибки «времени выполнения» существуют во всех типах программного обеспечения. Это приводит к сбою приложения, и Windows (или любая другая операционная система, которую вы используете) должна будет показать ошибку.

Зачастую, ошибка связана со ссылкой, сделанной на рабочий лист, объект, переменную или файл, которые не загрузились. Это относительно просто решается, но требует терпения и понимания процесса.

Решение проблемы

  • Основное решение «ошибки выполнения 424» — найти все ссылки в коде VBA. Лучший способ устранить ошибку 424 — использовать режим «отладки» VBA.
  • Самый простой способ сделать это — просмотреть каждую строку кода и удалить все возникшие проблемы. Есть простой способ сделать это, и он очень хорошо помогает исправить большинство ошибок 424 в VBA. Первое и самое эффективное решение — вручную «прочесать» код. Так можно удалить блоки кода по порядку. Второй метод — позволить VBA «пройтись» по вашему коду, удалив все элементы, которые могут вызывать проблемы.

Для автоматической проверки кода можно использовать функцию «пошагового выполнения кода», которая позволяет визуализировать, как работает каждая строка кода.

Заходим в редактор VBA.  Чтобы добраться до него сделайте следующее: Файл — Параметры — Настроить ленту. Затем проверьте, что установлен флажок «Разработчик». Это создаст вкладку «Разработчик» в верхней части экрана. Автоматически запустится поиск возникшей проблемы.

Простой алгоритм решения проблемы вручную:

  1. Найдите строку кода с нарушением
  2. Определите, ссылались ли вы на объекты, которые не объявлены
  3. Найдите любую из функций, которая может вызывать ошибку, и определите, что они вызываются правильно (с правильным синтаксисом).
  4. Удалите как можно больше кода, чтобы приложение снова заработало, а затем добавьте строки одну за другой (это изолирует ошибку и позволяет исправить любую из проблем, которые могут возникнуть).

Есть дополнительные вопросы?

Спроси у нас в комментариях. Мы позовем нашего администратора на помощь. В комментариях должна быть описана суть ошибки, скриншот ошибки.

VBA Object Required

Object Required in Excel VBA

Object required is an error which is caused at run time when we have defined any variable which is not an object but we try to assign some values using a SET statement. This error is a run time error that arises for various reasons. Though this error has its own causes there are also solutions for this error. Every method requires an object qualifier and these objects are assigned by using the SET statement. For example, if we have defined any variable which is not an object but we try to assign some values using a SET statement this will cause the error at run time which is object required error. There are also some instances when we do everything right have correct object qualifiers and valid object but we try to assign values to a read-only property then also we will encounter this error.

How to Handle VBA Object Required?

Out of the numerous reasons we saw for the cause of Object Required Error, there are ways in which we can handle this error.

  1. For the spell mistakes for the variables or the functions in the code, we can use Option Explicit statement to not encounter this error.
  2. We can check whether the object we are referring to it exists or not.
  3. Also, we need to ensure whether we have defined or declared our variables correctly or not.

You can download this VBA Object Required Excel Template here – VBA Object Required Excel Template

Example #1

Let us begin with the first example where this type of error might occur and it is when we misspell a function’s name. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Now we can declare our subprocedure.

Code:

Sub Example1()

End Sub

VBA Object Required Example 1-2

Step 3: Look at the code below what we have in the first example.

Code:

Sub Example1()

Application3.WorksheetFunction.Sum (Range("A1:A100"))

End Sub

VBA Object Required Example 1-3

Step 4: The application function has an extra character 3 with it and we run the above code we will encounter the following error.

VBA Object Required Example 1-4

Example #2

Now let us discuss an example where we will use to set an object where an object is not defined instead. In other words, we will treat a non-object feature as an object. For this, follow the below steps:

Step 1: We will start with another subprocedure.

Code:

Sub Example2()

End Sub

VBA Object Required Example 2-1

Step 2: Let us declare a variable for the path or a location to save as a string data type.

Code:

Sub Example2()

Dim your_path As String

End Sub

VBA Object Required Example 2-2

Step 3: Let us use the Set statement to set a path to this variable.

Code:

Sub Example2()

Dim your_path As String
Set your_path = "x/y/z"

End Sub

Set Path Example 2-3

Step 4: For this example’s sake let us use Msgbox function to see what the final result will be.

Code:

Sub Example2()

Dim your_path As String
Set your_path = "x/y/z"
MsgBox your_path

End Sub

Msgbox function Example 2-4

Step 5: When we execute the above code we will get the following result.

VBA Object Required Example 2-5

We received this error because we used SET statement to a string variable and VBA treated this variable as an object with the SET statement.

Example #3

Sometimes we encounter this error when we don’t use SET statement when we assign an object reference. Let us go through this example and see how it may occur. For this, follow the below steps:

Step 1: In the same module let us start with the procedure for example 3.

Code:

Sub Example3()

End Sub

VBA Object Required Example 3-1

Step 2: Declare any variable as a variant.

Code:

Sub Example3()

Dim ABC

End Sub

VBA Object Required Example 3-2

Step 3: Let us create an object using the Create Object statement.

Code:

Sub Example3()

Dim ABC
ABC = CreateObject("Excel.Application")

End Sub

Object statement Example 3-3

Step 4: Now we have assigned the object reference but instead of using the SET statement.

Code:

Sub Example3()

Dim ABC
ABC = CreateObject("Excel.Application")
ABC.Visible = True

End Sub

SET statement Example 3-4

Step 5: Once we execute the code above.

VBA Object Required Example 3-5

Example #4

Now there another chance when we encounter this error and that is when we try to assign values to a read-only property. Our object reference may be correct in this case but we will still encounter an error. Let us go through another example of how this might happen. For this, follow the below steps:

Step 1: In the same module let us begin.

Code:

Sub Example4()

End Sub

VBA Object Required Example 4-1

Step 2: Below is the sample code for using a string variable with an undefined variable.

Code:

Sub Example4()

Dim a As String
a = "Anand"
For i = 1 To l
With Age
Set a = Age
End With
Next i

End Sub

String Variable Example 4-2

Step 3: When we execute the code above we will see the following error.

VBA Object Required Example 2-5

We received this error because we tried to assign values to read-only properties. Let me explain the code first we started a loop from where we are assigning object references but we are using the read-only properties.

Explanation of VBA Object Required:

From the above examples, it is very clear to us that Object Required is a run time error in VBA which we encounter while making some very small mistakes to some huge mistakes in VBA. Error handling this error can be tricky, as some mistakes are hard to identify. But there are some preventive methods such as using the option explicit statement or using the SET statement to assign objects only.

Things to Remember

There are few things which we need to remember about VBA Object Required and they are as follows:

  1. Object Required is a type of run time error in VBA.
  2. This error has an error code as 424.
  3. Spelling mistakes for variables and functions can also be a cause of Object Required Error.
  4. When some variable is not defined as an object but it is used as an object we may encounter Object Required error.

Recommended Articles

This is a guide to the VBA Object Required. Here we discuss how to handle Object Required in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA CInt
  2. VBA AND
  3. VBA Filter
  4. VBA XLUP

Понравилась статья? Поделить с друзьями:
  • Microsoft visual foxpro error 1429
  • Microsoft visual basic runtime error 1004 как исправить
  • Microsoft visual c выдает ошибку runtime error
  • Microsoft visual basic run time error 438
  • Microsoft visual c runtime stray ошибка