Runtime error 404 vba

Ошибка "run-time error '424' object required" VBA Решение и ответ на вопрос 794339

Lendor

0 / 0 / 0

Регистрация: 13.02.2013

Сообщений: 34

1

25.02.2013, 11:58. Показов 65394. Ответов 9

Метки нет (Все метки)


в следующем коде в строке 4 (открытие файла с расширением doc) выскакивает ошибка «run-time error ‘424’ object required»

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
 Dim wdApp As Object
 Dim wdDoc As Object
 Set wdApp = CreateObject("Word.Application")
 Set wdDoc = wdApp.Documents.Open(Replace(ThisWorkbook.FullName, ThisWorkbook.Name, act_1058652.doc))
 wdApp.Selection.WholeStory
 wdApp.Selection.Copy
 Worksheets("Обработка").PasteSpecial Format:="HTML", Link:=False, DisplayAsIcon:= _
        False, NoHTMLFormatting:=True
 wdDoc.Close
 wdApp.Quit
Set wdDoc = Nothing
Set wdApp = Nothing

уже все перепробовал для того, чтобы она исчезла, и ставил дополнително к 2010 офису 2003, тк код пишется на 2003, а стоял у меня 2010, и биьлиотеки подключал в Tools-References, и в уровне безопасности макросов разрешил обращение к файлам из VBA, а ошибка так и вылазит (((
какие еще могут быть причины этой ошибки

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



693 / 99 / 10

Регистрация: 25.06.2011

Сообщений: 718

25.02.2013, 12:02

2

Эта проблема может возникнуть при следующих случаях:
Библиотека объектов доступа к данным не используется должным образом. — или —
Объект доступа к данным файлов отсутствуют, повреждены или неправильно зарегистрированы.

Добавлено через 42 секунды

Цитата
Сообщение от Lendor
Посмотреть сообщение

Replace(ThisWorkbook.FullName, ThisWorkbook.Name, act_1058652.doc)

попробуй просто прописать путь к файлу



0



Казанский

15131 / 6405 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

25.02.2013, 12:10

3

Лучший ответ Сообщение было отмечено как решение

Решение

Имя файла — в кавычках!

Visual Basic
1
Set wdDoc = wdApp.Documents.Open(Replace(ThisWorkbook.FullName, ThisWorkbook.Name, "act_1058652.doc"))



4



0 / 0 / 0

Регистрация: 13.02.2013

Сообщений: 34

25.02.2013, 12:23

 [ТС]

4

действительно кавычки)) спасибо



0



Казанский

15131 / 6405 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

25.02.2013, 15:31

5

А лучше так:

Visual Basic
1
Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "act_1058652.doc")

, потому что часть пути может совпадать с именем книги, например c:MyBook.xlsMyBook.xls, и при замене сформируется несуществующий путь.



0



mostApi

7 / 5 / 0

Регистрация: 15.05.2015

Сообщений: 342

02.11.2015, 15:18

6

Та же ошибка!
Обзываю

Visual Basic
1
Public Cmb1, Cmb2 As ComboBox

— есть альтернатива ComboBox?
Почему альтернатива?, или то что можно применить в случае?
Из диапазона ячеек поиском формируется список для ComboBox, потом из него по .ListIndex мне удобно задавать нужные координаты используемых ячеек?!
Ошибка здесь:

Visual Basic
1
2
3
4
5
6
7
8
With Cmb1
    '.Clear
    '.Style = fmStyleDropDownList
        For iRow = 14 To Cells(Rows.Count, 2).End(xlUp).Row Step 4
            .AddItem Cells(iRow, 2)
        Next
    .ListIndex = -1
End With

Добавлено через 46 минут

Visual Basic
1
Dictionary

— может словарь? Как с ним в моем случае быть?



0



Казанский

15131 / 6405 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

02.11.2015, 15:45

7

mostApi, а где Вы связываете Cmb1 с каким-либо существующим комбобоксом? Например

Visual Basic
1
Set Cmb1 = UserForm1.ComboBox1



1



7 / 5 / 0

Регистрация: 15.05.2015

Сообщений: 342

02.11.2015, 16:22

8

Казанский, Ооо, не подумал, спасибо…

Вопрос: собрал словарь, структура такова: Key = «Vasia»; Item = «Вася»… и т.д.
Как найти «Вася» и подставить с него «Vasia»…?



0



Казанский

15131 / 6405 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

02.11.2015, 23:05

9

Цитата
Сообщение от mostApi
Посмотреть сообщение

Как найти «Вася» и подставить с него «Vasia»…?

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

Visual Basic
1
2
3
4
5
6
  For Each x In di.Keys 'di - словарь
    If di(x) = "Вася" Then
      di(x) = x
      Exit For
    End If
  Next

А почему приходится искать значение? Может, поменять местами значение и ключ?



0



7 / 5 / 0

Регистрация: 15.05.2015

Сообщений: 342

03.11.2015, 11:23

10

Казанский, спасибо…

Просто у меня в таблице Excel имена пользователей на Русском языке, а в базе, таблица имени пользователя на English, поэтому нужна была простая подстановка…



0



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

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 и обратная связь.

Источник

VBA Object Required

By Madhuri Thakur

VBA Object functions

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.

Valuation, Hadoop, Excel, Mobile Apps, Web Development & many more.

  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.

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.

Step 2: Now we can declare our subprocedure.

Code:

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

Code:

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

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:

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

Code:

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

Code:

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

Code:

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

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:

Step 2: Declare any variable as a variant.

Code:

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

Code:

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

Code:

Step 5: Once we execute the code above.

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:

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

Code:

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

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 –

Источник

VBA Object Required

Object Required in Excel VBA

Mistakes are part and parcel of coding language. But the real genius lies in finding the error and fixing those errors. The first step in fixing those errors is the intelligence to find why those errors are occurring. If you can find why those errors are coming, then it is a very easy job to fix those errors without breaking a sweat. One such error in VBA Error In VBA VBA error handling refers to troubleshooting various kinds of errors encountered while working with VBA. read more coding is “Object Required.”

Table of contents

If you remember, while learning variables and assigning data types to those variables, we have “Object” data types as well. So, when the object data type is assigned, and if that object does not exist in the worksheet or workbook we refer to, we will get the VBA error message as Object required.” So, as a new coder, it is common to panic in those situations because, at the starting level, a beginner cannot find the cause for this error.

You are free to use this image on your website, templates, etc., Please provide us with an attribution link How to Provide Attribution? Article Link to be Hyperlinked
For eg:
Source: VBA Object Required (wallstreetmojo.com)

Why does Object Required Error Occur? (and… How to Fix it?)

It takes two or three examples to understand why this error occurs and how to fix it.

For example, look at the below code.

Code:

Let me explain to you the above code for you.

We have declared three variables, and the first two refer to the “Workbook” and “Worksheet” objects. The third variable refers to the “Date” data type.

When the “Object” data types assign the variable, we need to use the word “Set” key to assign the object’s reference to the variable. So, in the next two lines, by using the “Set” keyword, we have assigned the reference of “ThisWorkbook” to the variable “Wb” because this variable holds the object data type as “Workbook.” For the variable “Ws,” we have assigned the worksheet object of the “Data” worksheet in this workbook.

  • In the next line for the “Date” data type variable also, we have used the “Set” keyword to assign the value of the cell A1 value in this workbook (Wb) and the worksheet “Data” (Ws).
  • In the next line, we show the value of the “MyDate” variable value of cell A1 in the message box in VBA.
  • Let us run this code and see what we get.

As you can see above, it shows the VBA error message as “Object required.” Therefore, it is time to examine why we are getting this error message.

  • In the above error message image in the code section, while showing the error message, it has highlighted the error part of the code with blue color.

  • So, the question remains why we got this error. The first thing we need to see is this particular variable data type. Go back to the previous code line, assigning the data type to the variable “MyDate.”

  • We have assigned the variable data type as “Date” and now return to the error line.

In this line, we have used the keyword “Set,” whereas our data type isn’t the “Object” data type. So the moment VBA code sees the keyword “Set,” it assumes it is an object data type and says it requires an object reference.

So, the bottom line is the “Set” keyword one may use to refer only to reference the object variables like Worksheet, Workbook, etc.

Example #1

Now take a look at the below code.

Code:

In the above code, we have used the worksheet function “SUM” to get the total of the cell values from A1 to A100. When you run this code, we will encounter the below error.

It says, “Run-time error ‘424’: Object required.”

Now, let us closely look at the code now.

Instead of using “Application,” we mistakenly used “Application1”, so this encountered the error of “Object required” in the VBA code.

Things to Remember

  • The “Object required” means object data type reference needs to be accurate.
  • When the Option Explicit word is unenabled in the coding, we will get an “Object Required” error for misspelled variable words. If Option Explicit is enabled, we will get the variable not defined error for misspelled variable words.

Recommended Articles

This article has been a guide to VBA Object Required. Here, we learn why the object required an error in Excel VBA and some examples and download the Excel template. Below are some useful Excel articles related to VBA: –

Источник

 

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

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

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

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

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

 

Sanja

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

Сообщений: 14837
Регистрация: 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

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

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

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

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

 

FeelingThis

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

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

Jungl

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

 

Sanja

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

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

#10

23.09.2016 23:37:47

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

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

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

 

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

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

Сообщений: 13265
Регистрация: 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

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

Сообщений: 4328
Регистрация: 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

  • Home
  • Forum
  • Microsoft Office Application Help — Excel Help forum
  • Excel Programming / VBA / Macros
  • 404 Error

  1. 02-11-2019, 07:54 AM


    #1

    Biplab1985 is offline


    Forum Contributor


    Join Date
    05-19-2015
    Location
    Karnataka, INdia
    MS-Off Ver
    MS Office 2010
    Posts
    277

    404 Error

    Hi All,

    I have a code to copy paste range of cells multiple time,this works well when X=1 but return 404 error when i change x =3

    any help to fix will be of great help


  2. 02-11-2019, 08:15 AM


    #2

    Re: 404 Error

    How many rows of data did you select initially, and what format is your workbook — xls or a later format?


  3. 02-11-2019, 11:21 AM


    #3

    Biplab1985 is offline


    Forum Contributor


    Join Date
    05-19-2015
    Location
    Karnataka, INdia
    MS-Off Ver
    MS Office 2010
    Posts
    277

    Re: 404 Error

    Tried with 2 rows for 3 times.

    Format is Xlsm( MS 2013)


  4. 02-11-2019, 11:24 AM


    #4

    Re: 404 Error

    I suspect you’re overlapping the original range as you didn’t qualify the Cells property. Try this:


Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Replies: 5

    Last Post: 07-04-2018, 10:04 AM

  2. Replies: 3

    Last Post: 07-25-2014, 12:12 PM

  3. Replies: 7

    Last Post: 01-06-2014, 06:11 AM

  4. Replies: 4

    Last Post: 11-02-2012, 10:19 AM

  5. Replies: 2

    Last Post: 07-16-2012, 09:55 AM

  6. Replies: 14

    Last Post: 02-16-2011, 02:35 PM

  7. Replies: 9

    Last Post: 02-16-2006, 02:10 PM

Bookmarks

Bookmarks

All times are GMT -4. The time now is 09:58 PM.

Object Required in Excel VBA

Mistakes are part and parcel of coding language. But the real genius lies in finding the error and fixing those errors. The first step in fixing those errors is the intelligence to find why those errors are occurring. If you can find why those errors are coming, then it is a very easy job to fix those errors without breaking a sweat. One such error in VBAVBA error handling refers to troubleshooting various kinds of errors encountered while working with VBA. read more coding is “Object Required.”

Table of contents
  • Object Required in Excel VBA
    • Why Object Required Error Occurs? (and… How to Fix it?)
      • Example #1
    • Things to Remember
    • Recommended Articles

Object Required Error

If you remember, while learning variables and assigning data types to those variables, we have “Object” data types as well. So, when the object data type is assigned, and if that object does not exist in the worksheet or workbook we refer to, we will get the VBA error message as Object required.” So, as a new coder, it is common to panic in those situations because, at the starting level, a beginner cannot find the cause for this error.

VBA-Object-Required.png

You are free to use this image on your website, templates, etc., Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA Object Required (wallstreetmojo.com)

Why does Object Required Error Occur? (and… How to Fix it?)

It takes two or three examples to understand why this error occurs and how to fix it.

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

For example, look at the below code.

Code:

Sub Last_Row()

 Dim Wb As Workbook
 Dim Ws As Worksheet
 Dim MyToday As Date

 Set Wb = ThisWorkbook
 Set Ws = ThisWorkbook.Worksheets("Data")
 Set MyToday = Wb.Ws.Cells(1, 1)

 MsgBox MyToday

End Sub

Let me explain to you the above code for you.

We have declared three variables, and the first two refer to the “Workbook” and “Worksheet” objects. The third variable refers to the “Date” data type.

When the “Object” data types assign the variable, we need to use the word “Set” key to assign the object’s reference to the variable. So, in the next two lines, by using the “Set” keyword, we have assigned the reference of “ThisWorkbook” to the variable “Wb” because this variable holds the object data type as “Workbook.” For the variable “Ws,” we have assigned the worksheet object of the “Data” worksheet in this workbook.

Set Wb = ThisWorkbook
Set Ws = ThisWorkbook.Worksheets("Data")
  • In the next line for the “Date” data type variable also, we have used the “Set” keyword to assign the value of the cell A1 value in this workbook (Wb) and the worksheet “Data” (Ws).
Set MyToday = Wb.Ws.Cells(1, 1)
  • In the next line, we show the value of the “MyDate” variable value of cell A1 in the message box in VBA.
MsgBox MyToday
  • Let us run this code and see what we get.

VBA Object Required Example 1

As you can see above, it shows the VBA error message as “Object required.” Therefore, it is time to examine why we are getting this error message.

  • In the above error message image in the code section, while showing the error message, it has highlighted the error part of the code with blue color.

VBA Object Required Example 1-1

  • So, the question remains why we got this error. The first thing we need to see is this particular variable data type. Go back to the previous code line, assigning the data type to the variable “MyDate.”

VBA Object Required Example 1-2

  • We have assigned the variable data type as “Date” and now return to the error line.

VBA Object Required Example 1-3

In this line, we have used the keyword “Set,” whereas our data type isn’t the “Object” data type. So the moment VBA code sees the keyword “Set,” it assumes it is an object data type and says it requires an object reference.

So, the bottom line is the “Set” keyword one may use to refer only to reference the object variables like Worksheet, Workbook, etc.

Example #1

Now take a look at the below code.

Code:

Sub Object_Required_Error()

Range("A101").Value = Application1.WorksheetFunction.Sum(Range("A1:A100"))

End Sub

In the above code, we have used the worksheet function “SUM” to get the total of the cell values from A1 to A100. When you run this code, we will encounter the below error.

Example 2

It says, “Run-time error ‘424’: Object required.”

Now, let us closely look at the code now.

Example 2-1

Instead of using “Application,” we mistakenly used “Application1”, so this encountered the error of “Object required” in the VBA code.

If the word “Option ExplicitVBA option explicitly makes a user mandatory to declare all the variables before using them; any undefined variable will throw an error while coding execution. We can enable it for all codes from options to require variable declaration.read more” is enabled, we will get the “Variable not defined” error.

Example 2-2

Things to Remember

  • The “Object required” means object data type reference needs to be accurate.
  • When the Option Explicit word is unenabled in the coding, we will get an “Object Required” error for misspelled variable words. If Option Explicit is enabled, we will get the variable not defined error for misspelled variable words.

Recommended Articles

This article has been a guide to VBA Object Required. Here, we learn why the object required an error in Excel VBA and some examples and download the Excel template. Below are some useful Excel articles related to VBA: –

  • VBA Login User Form
  • CreateObject in VBA
  • OverFlow Error in VBA
  • 1004 Error in VBA
  • VBA COUNTA
Icon Ex Error Number: Runtime Error 404
Error Name: MDI child forms cannot be shown modally
Error Description: You may not set the modal option on an MDI child form.
Developer: Microsoft Corporation
Software: Windows Operating System
Applies to: Windows XP, Vista, 7, 8, 10, 11

MDI child forms cannot be shown modally Assessment

MDI child forms cannot be shown modally is often called as runtime error (bug). Software developers try to ensure software are free from these glitches until it is publicly released. Errors such as error 404 sometimes get dropped from reporting, leaving the issue remaining unresolved in the software.

In the release of the latest version of Windows Operating System, an error could be encountered that reads, «You may not set the modal option on an MDI child form.». At the time the error 404 is encountered, the end-user can report the issue to Microsoft Corporation. Microsoft Corporation will then patch these defective code entries and make an update available for the download. Therefore, when you encounter a prompt for a Windows Operating System update, it is usually because it’s a solution for fixing error 404 and other bugs.

How Runtime Error 404 Triggers, and What Is It?

A problem with Windows Operating System source code will produce this MDI child forms cannot be shown modally, most often during the startup phase. Let’s analyze some of the most common causes of error 404 runtime errors:

Error 404 Crash — This is a very popular error 404 runtime error that causes the entire program to shut down. Typically this is the result of Windows Operating System not understanding the input, or not knowing what to output in response.

MDI child forms cannot be shown modally Memory Leak — When a Windows Operating System memory leak happens, it will result in the operating system running sluggish due to a lack of system resources. Critical problems related to this may be lack of memory de-allocation, or there is a connection to bad code such as infinite loops.

Error 404 Logic Error — Software logic error occur when, despite the exact input from the user, a wrong output is produced. This happens when Microsoft Corporation’s source code causes a flaw in information handling.

The root causes of Microsoft Corporation errors associated with MDI child forms cannot be shown modally include a missing or corrupt file, or in some cases, a past or present Windows Operating System-related malware infection. Ordinarily, installing a new version of the Microsoft Corporation file will repair the problem creating the error. Furthermore, keeping your registry clean and optimized can prevent invalid file path (like MDI child forms cannot be shown modally) and file extension references, so we recommend running a registry scan cleanup regularly.

Classic MDI child forms cannot be shown modally Problems

Windows Operating System Complications with MDI child forms cannot be shown modally Comprise Of:

  • «MDI child forms cannot be shown modally Program Error.»
  • «Win32 Software Error: MDI child forms cannot be shown modally»
  • «Sorry, MDI child forms cannot be shown modally encountered a problem.»
  • «MDI child forms cannot be shown modally can’t be located.»
  • «MDI child forms cannot be shown modally not found.»
  • «Error starting program: MDI child forms cannot be shown modally.»
  • «MDI child forms cannot be shown modally is not running.»
  • «MDI child forms cannot be shown modally halted.»
  • «Software Path Fault: MDI child forms cannot be shown modally.»

Windows Operating System-involved MDI child forms cannot be shown modally issues happen during install, when MDI child forms cannot be shown modally-related software is running, startup or shutdown, or during the Windows installation process. It’s important to note when MDI child forms cannot be shown modally issues happen, as it helps troubleshoot Windows Operating System problems (and report to Microsoft Corporation).

Problem Sources of MDI child forms cannot be shown modally

Windows Operating System and MDI child forms cannot be shown modally issues come from missing or corrupt files, Windows registry invalid entries, and malware infections.

More precisely, MDI child forms cannot be shown modally errors created from:

  • Corrupted or invalid MDI child forms cannot be shown modally registry entry.
  • Virus or malware corrupting MDI child forms cannot be shown modally.
  • MDI child forms cannot be shown modally mistakenly deleted or maliciously by software unrelated to the Windows Operating System application.
  • Another program is in conflict with Windows Operating System and its shared referenced files.
  • Windows Operating System / MDI child forms cannot be shown modally corrupt from incomplete download or install.

Product by Solvusoft

Download Now
WinThruster 2022 — Scan your PC for computer errors.

Compatible with Windows 11, 10, 8, 7, Vista, XP and 2000

Optional Offer for WinThruster by Solvusoft | EULA | Privacy Policy | Terms | Uninstall

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Runtime error at 105 784 invalid floating point operation gta san andreas
  • Runtime error an attempt was made to access wizardform before it has been created
  • Runtime error 38446
  • Runtime error at 104 784 invalid floating point operation сталкер
  • Runtime error access violation

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии