Vba ошибка 424 object required как исправить

The first code line, Option Explicit means (in simple terms) that all of your variables have to be explicitly declared by Dim statements. They can be any type, including object, integer, string, or even a variant.

This line: Dim envFrmwrkPath As Range is declaring the variable envFrmwrkPath of type Range. This means that you can only set it to a range.

This line: Set envFrmwrkPath = ActiveSheet.Range("D6").Value is attempting to set the Range type variable to a specific Value that is in cell D6. This could be a integer or a string for example (depends on what you have in that cell) but it’s not a range.

I’m assuming you want the value stored in a variable. Try something like this:

Dim MyVariableName As Integer
MyVariableName = ActiveSheet.Range("D6").Value

This assumes you have a number (like 5) in cell D6. Now your variable will have the value.

For simplicity sake of learning, you can remove or comment out the Option Explicit line and VBA will try to determine the type of variables at run time.


Try this to get through this part of your code

Dim envFrmwrkPath As String
Dim ApplicationName As String
Dim TestIterationName As String

Если вы используете Excel, вы можете столкнуться с ошибкой «Ошибка выполнения 424» с сообщением «Требуется объект».

Это ошибка в VBA (Visual Basic для приложений) и в основном проявляется, когда вы указываете на объект, который либо не существует, либо не находится за пределами текущей области.

Если вы видите ошибку, когда кто-то «обрабатывает» какой-то макрос/автоматизированную функцию в электронных таблицах Excel, вероятная проблема заключается в том, что вы называете объект «вне контекста». Это означает, что вы можете загрузить объект, но его содержимое может быть изменено или изменено. Есть также некоторые другие потенциальные проблемы, которые я объясню в этом руководстве…

причина

Ошибка, которую вы видите, будет иметь следующее сообщение:

Ошибка времени запуска «424»

Требуется объект

Чтобы объяснить, почему он показывает ошибку и что это значит, Microsoft выпустила свой пакет «Visual Basic» в конце 90-х.

Это обеспечивало основные возможности системы, позволяя разработчикам-любителям создавать простые приложения. VB имел большой успех.

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

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

решение

Если вы хотите исправить проблему, вы должны сначала убедиться, что данные есть в системе, и тогда вы сможете правильно обращаться к ним. Этот урок объяснит, как:

1. Убедитесь, что переменные определены правильно

Основная проблема заключается в том, что вы вызываете метод для несуществующей переменной (объекта). Наиболее распространенная причина этого заключается в том, что вы просто неправильно вводите имя переменной и поэтому не объявляете ее в своем приложении VBA. Возьмем следующий пример:

Подтест ()

Application33.WorksheetFunction.Sum (диапазон (“A1: A100”))

Последняя подписка

Вышеприведенное вызовет ошибку, потому что вы пытаетесь вызвать метод WorksheetFunction для «Application33», указанного в объекте.

К сожалению, объект Application33 не существует в памяти, что не позволяет вашему приложению загрузить его. Чтобы исправить это, вам нужно просмотреть исходный код (почти всегда будут указаны неправильные ссылки) и исправить все имена объектов с ошибками.

2. Если вы используете Excel, убедитесь, что есть диапазоны/селекторы

Одна из наиболее распространенных причин ошибки заключается в том, что вы пытаетесь указать несуществующий объект или значение. Это типичная проблема при использовании одного из объектов VLookup или ActiveX. Если вы столкнулись с этой ошибкой, убедитесь, что код указывает только на существующие объекты:

Частный дополнительный тест ()

Это вызовет ошибку

Application.WorksheetFunction.VLookup(TeamName, Range (“TeamNameLookup”), 3, False).

Стоимость должна быть

Application.WorksheetFunction.VLookup(TeamName, Sheets (“YourSheetName”). Диапазон (“TeamNameLookup”), 3, False)

Последняя подписка

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

3. Убедитесь, что у вас есть правильные определения

Наконец, одна из наиболее распространенных причин ошибок заключается в том, что вы неправильно определяете свои переменные.

От неправильного определения переменных как неверных интерпретаций объектов до вызова «Option Explicit» вы можете пытаться указать переменные/объекты, которые не определены только потому, что они определены неправильно.

Например…

Вариант очевиден

Персональный дополнительный тест ()

Здесь вам нужно объявить переменные, прежде чем пытаться указать/заполнить их

Например…

Затемните your_path как строку

Установите your_path = “x/y/z”

Последняя подписка

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

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

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

puneet-gogia-excel-champs-09-06-23

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.

vba-object-required-error

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 the “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.

What is VBA

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

I’m trying to compare cell values between 2 Sheets (Sheet1 & Sheet2) to see if they match, and if they match move the matching values in Sheet1 to a pre-existing list (Sheet3) and delete the values in Sheet1 afterwards.

I’m using the reverse For Loop in Excel VBA, but everything works until the part where I start deleting the row using newrange1.EntireRow.Delete.

This throws a ‘424’ Object Required Error in VBA and I’ve spent hours trying to solve this, I’m not sure why this is appearing. Am I selecting the row incorrectly? The object?

Would appreciate if anyone can point me to the correct direction.

Here’s my code:

Sub Step2()

    Sheets("Sheet1").Activate

    Dim counter As Long, unsubListCount As Long, z As Long, x As Long, startRow As Long
    counter = 0
    startRow = 2
    z = 0
    x = 0

    ' Count Sheet3 Entries
    unsubListCount = Worksheets("Sheet3").UsedRange.Rows.Count

    Dim rng1 As Range, rng2 As Range, cell1 As Range, cell2 As Range, newrange1 As Range

    ' Select all emails in Sheet1 and Sheet2 (exclude first row)
    Set rng1 = Worksheets("Sheet1").Range("D1:D" & Worksheets("Sheet1").UsedRange.Rows.Count)
    Set rng2 = Worksheets("Sheet2").Range("D1:D" & Worksheets("Sheet2").UsedRange.Rows.Count)

   ' Brute Loop through each Sheet1 row to check with Sheet2
    For z = rng1.Count To startRow Step -1
        'Cells(z, 4)
        Set cell1 = Worksheets("Sheet1").Cells(z, "D")
        For x = rng2.Count To startRow Step -1
            Set cell2 = Worksheets("Sheet2").Cells(x, "D")

            If cell1.Value = cell2.Value Then ' If rng1 and rng2 emails match
                counter = counter + 1
                Set newrange1 = Worksheets("Sheet1").Rows(cell1.Row)

                newrange1.Copy Destination:=Worksheets("Sheet3").Range("A" & unsubListCount + counter)
                newrange1.EntireRow.Delete
            End If
        Next
    Next
End Sub

Here’s the error I’m getting:

424 Object Required

Various runtime errors can occur while running the VBA code in Microsoft Excel. One such error that you may receive when using the VBA is “runtime error 424′ object required.” Here’s how the error looks like:

Runtime Error 424' Object Required in Excel

In this blog, I will discuss the possible reasons and quick solutions for how to fix runtime error 424′ object required Excel. I will also allusion a professional Excel Repair Tool that will assist you in fixing this error if it has occurred due to corruption in the Excel workbook objects.

To fix corrupted Excel files, we recommend this tool:

This software will prevent Excel workbook data such as BI data, financial reports & other analytical information from corruption and data loss. With this software you can rebuild corrupt Excel files and restore every single visual representation & dataset to its original, intact state in 3 easy steps:

  1. Download Excel File Repair Tool rated Excellent by Softpedia, Softonic & CNET.
  2. Select the corrupt Excel file (XLS, XLSX) & click Repair to initiate the repair process.
  3. Preview the repaired files and click Save File to save the files at desired location.

When the VBA is unable to recognize the Excel workbook object for which you’re referring to a property, it displays you the error “Object Required.” The object can be the workbook, worksheet, class, macro, range, variable, etc.

On the other hand, we can say, that when you refer to the object, but a name of that object is incorrect then you can get this error. However, it occurs due to numerous reasons, such as:

  1. Missing objects in the workbook.
  2. When the object in the workbook is corrupted.
  3. The Excel Workbook is damaged or corrupted.
  4. Incorrect object name that you’re trying to state in the VBA code.
  5. Not using the Set statement when assigning the object reference.
  6. If the macros feature is disabled in Macro Security settings
  7. Using an incorrect command for an object statement.

Now, let’s proceed to the next section to learn how to fix object required error in VBA with the best methods.

How to Fix Runtime Error 424′ Object Required in MS Excel?

Below are some of the workable tricks that you can apply to resolve “object required” in MS Excel.

Quick Fixes:

  1. Check for Missing Object
  2. Check the Object Name
  3. Verify the Code
  4. Verify Macro Security Settings 
  5. Ensure All the References are in a Code
  6. Repair your Corrupt Excel Workbook
  7. One-Stop Solution: MS Excel Repair Software

Method 1- Check for Missing Object

As already mentioned in the causes, VBA is unable to recognize the workbook object for which you’re referring to a property due object is not available. In the illustration below, you can see that runtime error ‘424′ arises when the object named “Employee” isn’t available in the list of projects.

In such a case, you will have to check the object that is available and mention it in the code, like the below shown image:

Runtime Error 424' Object Required in Excel

Method 2- Check the Object Name

Apart from missing objects, this error can also occur when you attempt to run a code using the incorrect object name. For instance, an object name is- ‘MyObject’ but you are using “Backcolor”.

Runtime Error 424' Object Required in Excel

At that time, if you have to click on Debug option, the line with an error message will be highlighted. In order to solve it, provide a correct object name.

Runtime Error 424' Object Required in Excel

Method 3- Verify the Code

Since you are getting Excel VBA runtime error 424 object required userform while using the VBA code, you must check if there is any issue in the code. Because of missing or incorrect syntaxes, code contains uneven functions, and missing references can also lead to this issue. To fix the error, you can check and correct the code via opening a VBA editor.

Also Read: Fix VBA Error 400 Running An Excel Macro

Method 4- Verify Macro Security Settings 

In most of the cases, it has been seen that the macro feature is disabled in the Macro Security settings. It is possible that you are getting this Excel run time error due to a disabled macro feature. So, just follow the below steps to check & edit Macro Security settings:

  • Firstly, on a Developer tab, under Code section, you have to click on the Macro Security.
  • Now, the Trust Center window will appear, Choose the Macro Settings >> Enable all macros option >> Click OK.

enable all macros

If this solution won’t work, try the next one.

Method 5- Ensure All the References are Stated in a Code

Another option that you can try to troubleshoot runtime error 424′ object required Excel is to ensure that you have mentioned all the references in a code.

If you want to check this, then press the F5 key or Debug option to use the debug mode. After doing this, check if the issue is solved.

Method 6- Repair your Corrupt Excel Workbook

Corruption in an Excel workbook also triggers the “Object Required” error. To repair the file, you can use the Microsoft inbuilt utility (Open and Repair). Here are the complete steps to use this feature:

  • Open MS Excel >> Go to the File menu > Open.
  • Next, click on the Browse option to select an affected workbook.
  • Now, the Open dialog popup will appear. There, you have to click on a corrupted file.
  • After that, click the arrow opposite to the Open button >> choose Open and Repair.

excel open and repair 1

  • At this time, you will get a dialog box with 3 buttons – Repair, Extract Data, and Cancel.
  • Tap on Repair button to recover the data as much as possible.

excel open and repair

  • Once repaired, a message will be displayed on your screen. Simply click on the Close.

One-Stop Solution: MS Excel Repair Software

If the feature “Open and Repair” fails to get rid of the object required error in Excel, use an expert-recommended Excel Repair Tool. It is specially designed to fix Excel file (.xls, .xlsx, .xlsm, .xltm, and .xltx) corruption and recover all its components, such as macros, tables, queries, formulas, charts, etc. without modifying their original formatting.

Moreover, it repairs multiple MS Excel files in the single process. This tool supports all the Excel versions & can be downloaded on a Windows system.

Just download and install it on your PC from the below button to know how it works.

* Free version of the product only previews recoverable data.

Steps to Use This Tool

excel-repair-main-interface-1

stellar-repair-for-excel-select-file-2

stellar-repair-for-excel-repairing-3

stellar-repair-for-excel-preview-4

stellar-repair-for-excel-save-5

stellar-repair-for-excel-saving-6

stellar-repair-for-excel-repaired-7

previous arrow

next arrow

Summing Up

The “runtime error 424′ object required Excel” can trouble you & hamper your work. All you need to do is to try the workarounds mentioned in this article to troubleshoot it.

But if this error is associated with workbook object corruption, then you can opt for the Excel Repair Software to repair the corrupt Excel file object. You can even download the software’s free demo version to scan & preview the workbook objects.

Thanks for reading…!

Priyanka is a content marketing expert. She writes tech blogs and has expertise in MS Office, Excel, and other tech subjects. Her distinctive art of presenting tech information in the easy-to-understand language is very impressive. When not writing, she loves unplanned travels.

Понравилась статья? Поделить с друзьями:
  • Vba исключение ошибок
  • Vampire the masquerade bloodlines ошибка при установке
  • Vba если ошибка функция
  • Vdh002 macbook ошибка
  • Vba если ошибка то сообщение и конец макроса