Ошибка object required vba excel

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

 

FeelingThis

Пользователь

Сообщений: 5
Регистрация: 23.09.2016

#1

23.09.2016 23:24:49

Доброго времени суток. Столкнулся с такой проблемой, при выполнении выкидывает на выделенной строке с Run-Time Error «424»: Object Required:

Код
Sub Test() 
... 
Dim frmtRange As Range 
Set frmtRange = Range(Cells(1, BiggerColumn), Cells(LR, BiggerColumn + 1)) 
Format (frmtRange) 
End Sub 

Function Format(fRange as Range) 
... 
End Function

В чем может быть проблема? Грешу на третью строку, может неправильно задал объект frmtRange(переменные BiggerColumn и LR в порядке).

Изменено: FeelingThis23.09.2016 23:30:10

 

Sanja

Пользователь

Сообщений: 14850
Регистрация: 10.01.2013

А что Вы хотите от 4-й строки?

Согласие есть продукт при полном непротивлении сторон.

 

Sanja

Пользователь

Сообщений: 14850
Регистрация: 10.01.2013

Format — служебное слово VBA. В разных случаях это может быть функцией/свойством, и использование его в качестве названия для своей функции и есть ошибка

Согласие есть продукт при полном непротивлении сторон.

 

FeelingThis

Пользователь

Сообщений: 5
Регистрация: 23.09.2016

Чтобы в frmtRange записался диапазон данных Cells(1, BiggerColumn), Cells(LR, BiggerColumn + 1)
И затем все это дело отправилось на обработку в функцию

Изменено: FeelingThis23.09.2016 23:30:58

 

Jungl

Пользователь

Сообщений: 830
Регистрация: 18.01.2016

#5

23.09.2016 23:31:23

FeelingThis,

Код
arr = Format(frmtRange)
 

vikttur

Пользователь

Сообщений: 47199
Регистрация: 15.09.2012

FeelingThis, кнопка форматирования кода другая — <…>

Sanja, возможно, строка съехала

 

FeelingThis

Пользователь

Сообщений: 5
Регистрация: 23.09.2016

Спасибо за замечание, название функции поменял, но проблема не изчезла

 

Sanja

Пользователь

Сообщений: 14850
Регистрация: 10.01.2013

Вы присвойте результат работы Вашей функции чему нибудь, как пишет Jungl,
Да и саму UDF не помешало-бы посмотреть

Согласие есть продукт при полном непротивлении сторон.

 

FeelingThis

Пользователь

Сообщений: 5
Регистрация: 23.09.2016

Jungl

,
спасибо большое, это помогло

 

Sanja

Пользователь

Сообщений: 14850
Регистрация: 10.01.2013

#10

23.09.2016 23:37:47

Цитата
vikttur написал: возможно, строка съехала

в таком случае — от 5-й

Согласие есть продукт при полном непротивлении сторон.

 

Ігор Гончаренко

Пользователь

Сообщений: 13916
Регистрация: 01.01.1970

#11

23.09.2016 23:40:26

Цитата
название функции поменял, но проблема не изчезла

проблемы закончатся, когда Вы перестанете программировать

Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете!

 

FeelingThis

Пользователь

Сообщений: 5
Регистрация: 23.09.2016

#12

23.09.2016 23:42:15

Цитата
Sanja написал: в таком случае — от 5-й

требовалось передать диапазон в функцию

 

Jungl

Пользователь

Сообщений: 830
Регистрация: 18.01.2016

#13

23.09.2016 23:55:42

FeelingThis, смотря что вы хотите получить от функции, это вам виднее.
Ведь можно и обойтись передачей параметров оператору Sub через ByRef

Код
Sub Test()
Dim frmtRange As Range
Set frmtRange = Range(Cells(1, 1), Cells(2, 1))
Frmt frmtRange
End Sub
 
Sub Frmt(ByRef fRange As Range)
arr = fRange
End Sub
 

ZVI

Пользователь

Сообщений: 4338
Регистрация: 23.12.2012

#14

24.09.2016 02:44:56

Поясню, в чём проблема.
1. Сначала о синтаксисе. Вместо Frmt (frmtRange) должно быть либо Frmt frmtRange либо Call Frmt(frmtRange)
Обратите внимание на то, что VBA вставляет пробел в первом случае между Frmt и  (frmtRange), а в случае с Call пробела нет.
2. Теперь о преобразовании типов. Взятие в скобки переменной (см. первый случай) создает временную (runtime) переменную типа Variant, то есть меняет тип передаваемого в функцию параметра с Range на Variant, что и вызывает ошибку несоответствия типов.
Вот код для подтверждения такого преобразования типов:

Код
Sub Test1()
  Dim frmtRange As Range
  Set frmtRange = Range(Cells(1, 1), Cells(2, 1))
  Debug.Print TypeName(frmtRange), TypeName((frmtRange))
End Sub

Выдаст такое: Range         Variant()

Изменено: ZVI24.09.2016 02:47:17

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

Если вы используете 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)

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.

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)

Понравилась статья? Поделить с друзьями:
  • Ошибка ocf частотник шнайдер 312
  • Ошибка nvidia windows kernel mode driver
  • Ошибка nvidia streamer service что это
  • Ошибка ocf на частотном преобразователе schneider
  • Ошибка nvidia share не отвечает