Ошибка 424 в visual basic 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

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)

The Runtime error 424: Object required occurs when Excel is not able to recognize an object that you are referring to in a VBA code. The object can be a workbook, worksheet, range, variable, class, macro, etc. Some users have also reported that this error occurred when they tried to copy the values of the cells from one workbook to another.

Let’s understand the error through a small scenario. Suppose, I want to check the last field row in a table in a spreadsheet named “First” using the VBA code. To do this, I have added a command button and double-clicked on it and entered the below code in the backend:

Private Sub CommandButton2_Click()

Dim LRow As Integer

LRow = Worksheets(«First»).Cells(Rows.Count, 2).End(xlUp).Row

MsgBox («Last Row » & LRow)

End Sub

 Code On Command Button

In this code, Worksheets(«First») is a data object. If I mistakenly delete this data object and insert any random name (for example — kanada), then it will not be recognized by Excel. When I run this code, I will get the “Run-time error 424”.

Runtime Error with scenario 

Causes of Runtime Error 424 in Excel

The Runtime error 424: Object required can occur due to the following reasons:

  • Incorrect name of the object you are trying to refer to in a code.
  • You have provided an invalid qualifier to an object.
  • You have not used the Set statement while assigning an object reference.
  • The object is corrupted.
  • Missing objects in a workbook.
  • Objects you are trying to call in a code are mistakenly deleted or unavailable.
  • You have used an incorrect syntax for object declaration.
  • You are trying to perform an invalid action on an object in a code.
  • Workbook is corrupted.

 Solutions to Fix Runtime Error 424: Object Required in Excel

The VBA error ‘object required’ may occur due to different reasons. Based on the reason, you can follow the solutions mentioned below to fix the error.

1. Check the Name of the Object

The Runtime error 424 can occur when you run the VBA code using an incorrect name of the object. For example, the object name is ‘MyObject’ but you’re using “Backcolor”.

 Error When Incorrect Name Of The Object

 When you click the Debug button, the line with the error will highlight.

 Highlighting Line With Error

To fix the issue, you need to provide the correct name of the object.

2. Check if the Object is Missing

 The Runtime error 424 can occur if the object you are referring to as a method is not available or you are using the wrong object in a code. In the below example, you can see that the error occurs when an object named “Employee” is not available in the Project list.

 Example Of Code When Object Is Not Available

 You can check and mention the object which is available. For instance, Sheet2 in the below code.
Check When The Object Is Available

3. Check All References are Declared in the Code

You can get the Runtime error 424 if all the references are not declared. So, make sure you have declared all the references in the code. To verify this, you can use the debug mode by pressing F5 or clicking on the Debug option.

 Debug Command In Excel

4. Check the Macro Security Settings 

Sometimes, the error can occur if macros are disabled in the Macro Security settings. You can check and change the settings by following these steps:

  • On the Developer tab, in the Code section, click Macro Security.
  • In the Trust Center window, select Enable all macros.

 Macro Security Wizard

  • Click OK.

 Enable All Macro In Trust Center

  1. Repair your Workbook

Sometimes, the ‘Object required’ error can occur if your Excel file is damaged or corrupted. In such a case, you can try repairing the file using Microsoft’s in-built utility — Open and Repair. To use this utility, follow these steps:

  • In Excel, go to File > Open > Browse
  • In the Open dialog box, click on the corrupted Excel file. 
  • Click the arrow next to the Open button and select Open and Repair from the dropdown.
  • Select Repair to recover as much data from the file as possible.

If the Open and Repair utility fails or stops working, then you can try a professional Excel repair tool, such as Stellar Repair for Excel. It is an advanced tool that can repair severely corrupted Excel files (.xls, .xlsx, .xltm, .xltx, and .xlsm). It helps recover all the file components, including images, charts, tables, pivot tables, cell comments, chart sheets, formulas, etc., without impacting the original structure. 

Conclusion

The Runtime error 424 usually occurs when there is an issue with the objects in your VBA code. In this article, we have covered some effective methods to resolve the “object required” error in Excel. If the error occurs due to corruption in Excel file, then you can repair the corrupt file using Stellar Repair for Excel. It is a reliable tool that can repair severely corrupted Excel file without changing its actual formatting. You can download the free trial version of the software to evaluate its functionality.

Embark on a journey through the enigmatic world of VBA as we unravel the mysteries of the «Object Required» error. Brace yourself for an exhilarating exploration where clarity replaces confusion and error messages become stepping stones to mastery.

In this captivating quest, we delve deep into the heart of VBA’s Object Required error, demystifying its origins and shedding light on its solutions. Discover why this error occurs, how to identify its causes, and most importantly, how to conquer it with grace.

No longer will you be perplexed by cryptic error messages. Armed with knowledge and expertise, you’ll navigate through the complexities of object references, variable declarations, and object-oriented programming concepts. Watch as your code transforms from error-prone to robust, from frustrating to flawless.

But it doesn’t stop there—prepare to be amazed by a treasure trove of tips and techniques. Learn how to validate object assignments, handle null values, and gracefully recover from the Object Required error. Witness firsthand how troubleshooting becomes a skill, and errors become stepping stones to growth.

Whether you’re a beginner or a seasoned VBA enthusiast, understanding the Object Required error is a crucial step towards becoming a master programmer. Embrace the challenges, overcome the obstacles, and unlock a world where errors become opportunities for learning and growth.

So, are you ready to conquer the Object Required error? Join us on this thrilling journey of unraveling its complexities, understanding its nuances, and emerging as a master troubleshooter. Get ready to elevate your VBA programming skills and embrace a world where errors no longer hold you back.

  • The ‘Object Required’ Error In VBA
  • Why Does The ‘Object Required’ Error Occur?
  • Case Studies Of ‘Object Required’ Error
  • How To Detect The ‘Object Required’ Error
  • Troubleshooting The ‘Object Required’ Error
  • Important disclosure: we’re proud affiliates of some tools mentioned in this guide. If you click an affiliate link and subsequently make a purchase, we will earn a small commission at no additional cost to you (you pay nothing extra). For more information, read our affiliate disclosure.

    Imagine this: You’ve been laboring away on your VBA project, hammering away at your keyboard like Beethoven composing his 5th symphony, when suddenly, the harmony crumbles into disarray. The dreaded ‘Object Required’ error message pops up on your screen, a sour note in your otherwise melodious VBA composition. Well, my dear readers, let’s take the beast by the horns, demystify this error, and put you back in the composer’s seat.

    What Is The ‘Object Required’ Error?

    The ‘Object Required’ error, or Error 424 to put it more formally (not to be confused with Beverly Hills 90210), is one of VBA’s ways of telling you, «Hey, you’re trying to use an object here, but I have absolutely no idea what object you’re referring to.» It’s like trying to introduce someone at a party who isn’t actually there. Awkward, right?

    This error generally manifests when you’re trying to set a standard variable to an object but without using the ‘Set’ keyword. Consider it VBA’s «You must be this tall to ride» sign. No ‘Set’? No ride.

    Common Scenarios Where ‘Object Required’ Error Might Occur

    Let’s visit our friend Bob, a hardworking financial analyst. Bob is developing a VBA code to automate some of his tedious tasks. One day, Bob decides to create a code to automate the creation of pivot tables. He writes a line of code, confident in his abilities:

    myPivotTable = ActiveSheet.PivotTables.Add(...)

    But lo and behold, Bob is met with the uninviting face of the ‘Object Required’ error. Why? Because VBA expected him to use ‘Set’ before assigning an object to a variable. Here’s how he should have written it:

    Set myPivotTable = ActiveSheet.PivotTables.Add(...)

    But the error can also rear its head in other scenarios. Maybe you’re trying to use an object that doesn’t exist. Or perhaps you’re attempting to use an object that hasn’t been instantiated yet. It’s like VBA is a picky eater refusing to eat its vegetables unless they’re prepared just right.

    Below is an example of a scenario where ‘Object Required’ might occur. For simplicity’s sake, let’s compare these two examples side-by-side in a table.

    Incorrect Code (Error) Correct Code
    myRange = Worksheets("Sheet1").Range("A1:A10") Set myRange = Worksheets("Sheet1").Range("A1:A10")

    In this example, our missing ‘Set’ keyword strikes again. You see, in the world of VBA, the ‘Set’ keyword is a bit like a magic wand. It has the power to transform a simple variable into an object, opening a world of possibilities. Without it, you’re left standing at the entrance of the magic show, ticketless and forlorn.

    Why Does The ‘Object Required’ Error Occur?

    In the grand theatre of VBA, objects are the main characters. But if the script (that’s your code) doesn’t clearly mention who should be on stage at a given time, chaos ensues. This is what we call a missing or incorrect object reference.

    For instance, consider this line of code:

    Worksheets("Sheet1").Range("A1:A10").Font.Bold = True

    Seems harmless enough, right? But wait! If the worksheet «Sheet1» doesn’t exist, VBA gets as confused as a chameleon in a bag of skittles. The result? Our old friend, the ‘Object Required’ error, pops up to say hello.

    The Role Of ‘Set’ In Object Assignment

    Here’s a question for you: what do VBA and a posh British gentleman have in common? They both love to ‘Set’ things. Yes, the ‘Set’ keyword is a crucial part of object assignment in VBA. It’s like the ceremonial ribbon-cutting before a grand opening. Without it, the event just feels… incomplete.

    Let’s say you’re working on a code like this:

    myRange = Worksheets("Sheet1").Range("A1:A10")

    Without the ‘Set’ keyword, VBA looks at this line of code like a dog being shown a card trick. It simply doesn’t compute. The correct way to charm VBA into cooperation looks like this:

    Set myRange = Worksheets("Sheet1").Range("A1:A10")

    In the first case, you’re basically trying to fit a square peg (an object) into a round hole (a standard variable). The ‘Set’ keyword is the magical tool that makes the square peg round, so it fits perfectly.

    Getting Ahead Of Yourself: Using An Object Before It’s Instantiated

    In the world of VBA, timing is everything. Trying to use an object before it’s been instantiated is like trying to drink a cup of tea before it’s been brewed. Sure, you can drink the hot water, but it’s not quite the tea you were hoping for, is it?

    To illustrate this point, let’s peek into the life of Alice, a diligent data scientist. Alice is working on a project, and she writes the following line of code:

    myChart.SeriesCollection(1).Name = "Sales"

    Alice is confident this will work. However, if the chart doesn’t already have at least one series, VBA will respond with an ‘Object Required’ error. It’s VBA’s way of saying, «Alice, darling, you’re putting the cart before the horse.»

    Here’s how Alice can avoid this issue:

    With myChart.SeriesCollection.NewSeries
        .Name = "Sales"
        .Values = Worksheets("Sheet1").Range("A1:A10")
    End With
    

    In the corrected code, Alice makes sure a new series is created before she attempts to assign a name to it. It’s like ensuring the tea is properly brewed before taking that first, satisfying sip.

    🔉

    Remember, friends, VBA is a stickler for details. Incorrect or missing object references, forgetting the ‘Set’ keyword, or using an object before it’s ready can all lead to the dreaded ‘Object Required’ error. But with a little patience and a keen eye for detail, you can avoid these pitfalls.

    When VBA Meets a Non-existent Object

    Let’s now turn our attention to another curious scenario. Here, you’re trying to use an object that, in the eyes of VBA, doesn’t exist at all. It’s like expecting to find a unicorn in your backyard. Sure, it would be wonderful, but VBA isn’t a great believer in mythical creatures.

    Consider this line of code:

    Worksheets("My Precious").Range("A1:A10").Font.Bold = True

    This line of code would work perfectly if there were a worksheet named «My Precious.» But if there isn’t, VBA is as lost as a hobbit in Mordor. VBA can’t bold the font of a range in a worksheet that doesn’t exist. This would result in an ‘Object Required’ error because, well, the required object is missing.

    Objects And Collections: The Mystery Of The Missing Item

    VBA loves organization. It likes to keep related objects in neat little groups called collections. However, if you try to refer to an item in a collection that doesn’t exist, VBA gets as flustered as a librarian with books misplaced.

    Here’s an example:

    myShape = ActiveSheet.Shapes("MyShape")

    If «MyShape» doesn’t exist in the shapes collection of the active sheet, VBA will flash the ‘Object Required’ error. It’s like trying to borrow a book that isn’t in the library—frustrating for all involved.

    Case Studies Of ‘Object Required’ Error

    Meet Alex, a financial analyst with a love for spreadsheets and a penchant for VBA. One day, while working on a new VBA project, Alex encounters the ‘Object Required’ error. The line of code in question is:

    Worksheets("Revenue").Cells(1, 1).Value = "Total"

    On a hunch, Alex checks his workbook and realizes there’s no worksheet named «Revenue». It’s as if he’s trying to knock on a door that doesn’t exist. Alex promptly creates a worksheet named «Revenue», and lo and behold, the error vanishes.

    The Curious Case Of The Unset Object

    Next, we have Bailey, a data scientist known for her analytical mind and her fondness for tea. One afternoon, as she’s working on a VBA project, she runs into the ‘Object Required’ error. The line of code causing this hiccup is:

    myRange = Worksheets("Data").Range("A1:A10")

    Bailey, remembering her VBA basics, quickly spots the missing ‘Set’ keyword. She corrects the line to:

    Set myRange = Worksheets("Data").Range("A1:A10")

    And just like that, the error is as gone as a cookie at a tea party.

    The Mystery Of The Non-existent Chart Series

    Charlie, a quality controller with a knack for problem-solving, is our next case study. While working on a VBA project, Charlie comes across the ‘Object Required’ error. The culprit is this line of code:

    myChart.SeriesCollection(1).Name = "Quality"

    On careful inspection, Charlie realizes he’s trying to name a series that doesn’t exist. It’s akin to trying to name a star that hasn’t been discovered yet. Charlie modifies his code to:

    With myChart.SeriesCollection.NewSeries
        .Name = "Quality"
        .Values = Worksheets("Quality").Range("A1:A10")
    End With
    

    With these changes, the error is solved, and Charlie can go back to ensuring quality in peace.

    The Riddle Of The Missing Shape

    Our final case study involves Dana, a business analyst with an eye for detail. Dana encounters the ‘Object Required’ error while working on a VBA project. The line of code causing the issue is:

    myShape = ActiveSheet.Shapes("MyShape")

    Upon investigation, Dana realizes that there’s no shape named «MyShape» on the active sheet. It’s like trying to find Waldo when he’s not even in the picture. Dana adds the shape to the sheet, and the error disappears.

    in the VBA world, every error solved is a step closer to becoming a VBA whiz.

    The Unanticipated Early Exit

    Finally, let’s discuss Elliot, a teacher who uses VBA to automate grading. When he stumbles upon the ‘Object Required’ error, he’s puzzled. The line of code causing the confusion is:

    If rng.Value = "Fail" Then Exit Sub

    Our dear Elliot is trying to exit a subroutine prematurely when a condition is met. However, he forgot to define ‘rng’ before using it. It’s like trying to read a book before opening it. So, Elliot corrects his code to:

    Set rng = Worksheets("Grades").Range("B2")
    If rng.Value = "Fail" Then Exit Sub
    

    And, presto! The error is resolved, and Elliot can go back to grading in peace.

    How To Detect The ‘Object Required’ Error

    V. How To Detect The ‘Object Required’ Error

    The first step in detecting the ‘Object Required’ error is to run your VBA code. Now, if you’ve got a VBA script as long as War and Peace, this might seem like trying to find a needle in a haystack. But remember, every journey starts with a single step, or in this case, a single click of the ‘Run’ button.

    Note Down The Line Of Code

    When VBA encounters the ‘Object Required’ error, it’ll kindly highlight the offending line of code. It’s like a spotlight on a stage, pointing right at the issue. Note down this line of code, as it will be key to your investigation.

    Understand The Role Of The Line

    Now that you’ve identified the line causing the error, it’s time to understand its role. What is it trying to do? Is it setting a range? Is it referring to a worksheet or a workbook? Does it involve a shape, a chart, or some other object?

    Think of this as trying to understand the motive in a crime novel. The better you understand the role of the line, the closer you’ll be to spotting the error.

    Examine The Objects

    The ‘Object Required’ error often arises when there’s an issue with the objects in your VBA script. So, take a closer look at the objects in the offending line. Are they defined correctly? Do they exist? Are you using the ‘Set’ keyword where necessary?

    This step is a bit like a detective questioning the suspects in a case. You’re trying to find out if any of your objects are giving you false information.

    Check The Collections

    If your VBA script involves collections (like Worksheets or Charts), make sure you’re referring to items that actually exist in these collections. It’s like trying to pick a book from a shelf — it’s only possible if the book is there in the first place.

    Correct The Error

    Once you’ve identified the cause of the error, it’s time to correct it. This could involve adding the ‘Set’ keyword, correcting the name of an object, or ensuring an object exists before trying to use it.

    Troubleshooting The ‘Object Required’ Error

    The first step in troubleshooting the ‘Object Required’ error is to validate your objects. Ensure they exist and are defined correctly. It’s a bit like checking your ingredients before you start cooking. You wouldn’t want to find out halfway through that you’re missing eggs for your omelet, would you?

    Use The ‘Set’ Keyword

    When assigning an object to a variable, remember to use the ‘Set’ keyword. It’s like putting a label on a box, telling VBA exactly what’s inside. So, if you’re getting the ‘Object Required’ error, check to see if you’ve forgotten to use ‘Set’ in your assignment.

    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")
    

    Check Your Collections

    If your VBA script involves collections (like Worksheets or Charts), ensure you’re referring to items that exist. It’s like ensuring you’re picking a channel that’s included in your cable subscription. You wouldn’t want to sit down to watch a movie, only to find that you don’t get the channel it’s on, would you?

    Test Your Assumptions

    In VBA, assumptions can lead to errors. So, test your assumptions. If you assume an object exists, a worksheet is active, or a range is selected, verify these assumptions. It’s like checking the weather before going on a picnic. Just because it’s sunny now doesn’t mean it won’t rain later!

    Use Error Handling

    Sometimes, the ‘Object Required’ error might be caused by a line of code that can fail under certain conditions. In these cases, consider using error handling to manage these potential issues. It’s like carrying an umbrella just in case it rains — you hope you won’t need it, but you’re glad to have it if you do.

    On Error Resume Next
    'Your code here
    On Error GoTo 0
    

    Preventing The ‘Object Required’ Error

    The first line of defense against the ‘Object Required’ error is understanding your objects. The more you know about your objects, the less likely you are to misuse them. It’s like getting to know your car — the more you understand about how it works, the less likely you are to put diesel in a petrol engine (and vice versa).

    Set, Don’t Forget

    😝

    Remember to use the ‘Set’ keyword when assigning an object to a variable. Think of ‘Set’ as the VBA version of a seatbelt — it keeps your objects securely in place during the bumpy ride of your VBA code execution.

    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")
    

    Double-Check Your Collections

    If you’re dealing with collections like Worksheets, Forms, or Charts, always double-check that the items you’re referring to exist. It’s a bit like checking your shopping list before you leave the house — you don’t want to get to the store and realize you’ve forgotten what you came for.

    Test Your Assumptions

    In VBA, as in life, assumptions can lead to errors. If you’re assuming an object exists, a sheet is active, or a range is selected, it’s always a good idea to check these assumptions. Think of it as a kind of «trust, but verify» approach to your VBA code.

    Embrace Error Handling

    Using error handling in your VBA scripts can help manage potential issues that could lead to the ‘Object Required’ error. It’s like taking out insurance — you hope you’ll never need it, but you’re glad to have it when you do.

    On Error Resume Next
    'Your code here
    On Error GoTo 0
    

    As we’ve seen, preventing the ‘Object Required’ error involves a combination of understanding your objects, correct use of the ‘Set’ keyword, double-checking your collections, testing your assumptions, and using error handling. These steps can make your VBA journey a smooth and error-free one. After all, an ounce of prevention is worth a pound of cure. So remember, write smart, write safe, and keep those VBA errors at bay!

    TESTING YOUR KNOWLEDGE:

    Interactive Quiz

    What causes the «Object Required» error in VBA and how can it be resolved?

     

    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

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

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

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

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

     

    Sanja

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

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

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

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

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

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

     

    FeelingThis

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

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

    Jungl

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

     

    Sanja

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

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

    #10

    23.09.2016 23:37:47

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

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

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

     

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

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

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

    Понравилась статья? Поделить с друзьями:
  • Ошибка 424 в vba excel
  • Ошибка 424 vba что это
  • Ошибка 4239 камаз камминз евро 5
  • Ошибка 4221 в терминале сбербанка
  • Ошибка 422 что это значит