Excel vba compile error sub or function not defined

What’s worse than getting a runtime error in Excel VBA? A compile error. That’s because the actual error is not always highlighted, rather the opening Sub or Function statement. “Sub or Function not Defined” indicates a compile error. VBA displays this message when it cannot

What’s worse than getting a runtime error in Excel VBA? A compile error. That’s because the actual error is not always highlighted, rather the opening Sub or Function statement. “Sub or Function not Defined” indicates a compile error. VBA displays this message when it cannot find what is referenced by name. This article gives several examples of this compile error and how to correct them.

popup message box showing compile error: sub or function not defined

VBA is compiled (translated) into machine language before it is executed. Compile errors halt the compile process before procedures are executed.

Best practice:  Frequently check for compile errors from VB Editor. From the Debug menu, choose Compile VBAProject. No news is good news when nothing seems to happen.

Issue 1: Typos

Typos are the most common cause of “Sub or Function not Defined.” If Excel highlights (in yellow or gray) the keyword or procedure it can’t find, you have a great head start on your game of Hide and Seek.

Best practice:  Follow Microsoft’s naming convention and always include at least one capital letter whenever you create a name (exception: counter variables like n). Always type the name in lower case. When you leave the statement, and the name stays in all lower case, you have found a typo.

Contrary to its message, “Sub or Function not Defined” is not limited to procedures. The statement below causes this message. Can you find the typo?

          Worksheet("Summary").Select

Worksheets is the required keyword. The “Summary” worksheet object is a member of the Worksheets collection. The Worksheets collection contains all the worksheet objects of a workbook. Excel VBA has several collections.

Tip: All VBA collections end with “s”:  Workbooks, Sheets, Cells, Charts, etc.

Issue 2: Worksheet Functions

VB Editor may be the backstage to the worksheets in front, but not all worksheet props have been brought backstage. These “props” are functions that don’t exist in VBA. Worksheet functions like CountA cause “Sub or Function not Defined”:

          intCount = CountA("A:A")

The WorksheetFunction object is the “stage hand” that lets you call worksheet functions from VBA, like this:

          intCount = WorksheetFunction.CountA("A:A")

Issue 3: Missing Procedure

Less frequently, the called procedure is truly missing. After you check for typos, and you’re sure you coded the called procedure, perhaps you are missing a library. Tools, References is the next place to look.

From VB Editor Tools menu, choose References. The References dialog box opens. If VBA has identified a missing library, the last library with a checkmark will start with MISSING, followed by its name. Most of the time, you can simply scroll down the alphabetical list of libraries and check the missing library, then choose OK.

Fortunately, a missing library happens infrequently, usually related to a recent change. Perhaps you upgraded to a newer version of Excel. You purchased a new computer. You received a workbook from someone with an older version of Excel. Or you created your first macro that calls Solver Add-In.

The Solver project is not added to VBA when you enable the Solver Add-In, as shown below. At Solver project is near the top of the list of references, so you don’t have to scroll down to find it.

the references dialog box in vba

Your own macro workbooks can behave like Solver. Every Excel workbook has a built-in VBAProject. See MyFunctions in the screenshot above? MyFunctions is simply VBAProject renamed in a macro workbook. The workbook is open, so the Subs in MyFunctions run from the Developer tab. Even so, “Sub or Function not Defined” occurs when MyFunctions is not checked, and a procedure is called from a different macro. Simply check its project as an available reference.

Best practice:  Assign your VBA projects a meaningful name. From Project Explorer, right click the macro workbook. Choose VBAProperties, then type a Project Name with no spaces.

Issue 4: Unavailable Procedures

“Sub or Function not Defined” also occurs when the procedure is not available to the calling procedure in the same workbook. This error is related to Public vs. Private procedures. By default, Sub and Functions in standard modules of the Modules folder (seen in Project Explorer) are public. Standard procedures can be called by any procedure in the project. You can make a procedure private by adding the Private keyword, like this:

          Private Sub Initialize()

Tip:  All the macros shown in the Macros dialog box of the Developer tab are Public. The list excludes public functions.

Subs and Functions in worksheet modules are private. They can only be called from the worksheet (like clicking a button) or another procedure in that module. The same is true for user forms.

You can remedy “Sub or Function not Defined” by deleting the Private keyword from a procedure in a standard module. Sorry, you cannot remedy calling a procedure in a worksheet module from another module. Think of standard modules like public parks, and worksheet modules like private property. No trespassing allowed!

Issue 5: Declaring a Routine That Doesn’t Exist in the Specified DLL

The sub you’re trying to use could be a part of a DLL that needs to be referenced. So not declaring a DLL or declaring the wrong one will cause the compiler to not find the sub or function that you are trying to use.

A DLL is a dynamically linked library of a body of code that is compiled and is meant to provide some functionality or data to an executable application (like the VBA project we’re working with). A dynamic library is loaded by the VBA project when it needs it. DLLs are used in order to save developers time by utilizing built and tested bodies of code.

You will need to do some research to determine the library that your sub or function belongs to, then declare it in your code using the Declare keyword in its simplest form:

Declare Sub sub_name Lib “library_name”

To read more about accessing DLL functions and subs from VBA, check out: https://docs.microsoft.com/en-us/office/client-developer/excel/how-to-access-dlls-in-excel

Issue 6: Forgetting to Write It

Finally, it’s possible that it just hasn’t been written yet!

If you realize that the sub that has been highlighted for you by the VBA compiler doesn’t exist, then the solution is to create it. To know whether it exists or not, just search for it on the project level using the Find tool in the VBA IDE.

vba IDE find button

Selecting the ‘Current Project’ scope will allow you to search for the sub in the entire workbook. You can also do that for the other workbooks where the sub might reside.

searching for a particular sub in the vba ide

Wrap Up

“Sub or Function not Defined” is a compile error that occurs when VBA cannot find a procedure or other reference by name. A typo is the most common cause of this message.

See also: Compile Error: Expected End of Statement and Compile Error: User-defined Type Not Defined

Additional assistance from Mahmoud Mostafa

Return to VBA Code Examples

This article will explain the VBA sub or function not defined error.

vba sub not defined

When one has finished writing VBA code, it is a good idea to compile the code to check if there are any errors that may occur when running the code. If there are compile errors, a compile error warning will appear. One of these errors may be the Sub or Function not defined error. There can be a few reasons that this error occurs.

Misspelled Sub or Function

The most common reason for this error occurring is a spelling mistake!

Let us take the code below as an example:

Function GetTaxPercent(dblP as Double) As Double
  GetTaxPercent = dblP*0.15
End Function
Sub GetPrice()
  Dim dblPrice As Double
  Dim dblTax As Double
  dblPrice = Range("A1")
  dblTax = GetTaxPerc(dblPrice)
End Sub

In the above example, we have created a function to fetch the tax percentage value (15%).

In the second procedure, I am trying to call that function to get the tax on a certain value in range A1.

vba sub not defined spell

However, when I run the code, I get the compile error as I have spelt the function that I am calling incorrectly. This is an easily made mistake, especially in large VBA projects with lots of procedures and modules. The best way to prevent these errors at run time, is to compile the code before releasing it to your users.

In the Menu, click Debug > Compile VBAProject.

vba sub not defined compile

Any compile errors will then be highlighted in the code in order for you to fix them.

Missing Sub or Function

It may be that a sub or function just does not exist! Once again, if you have a large VBA project, it can be possible to delete a sub or function by mistake. If this is the case, you would unfortunately need to re-write the function. Always a good idea to have backups for this reason!

Incorrect Scope of Sub of Function

It may be the case that the sub or function does exist, and is spelt correctly, but the scope of the sub or function is incorrect. In the example below, the GetTaxPercent function is in a different module to the GetPrice sub that is calling it, and it has been marked Private. It therefore cannot be seen by the GetPrice sub procedure.

vba sub not defined scope

If we remove the word private in front of the Function, then the module will compile.

vba ambiguous compiled

Sub SM_Z()  
‘  
‘ Макрос записан 02.03.2005 (Efimov)  
‘  
   FRM = «=MAX(‘[Список студентов.xls]Список групп’!R4C1:R13C1)»
   Range(«B5»).Formula = FRM  
   m = 3 + Range(«B5»).Value  
   ActiveSheet.Shapes(«Group»).Select  
   With Selection  
       .ListFillRange = «‘[Список студентов.xls]Список групп’!$B$4:$B$» & m
       .LinkedCell = «$I$3»  
       .DropDownLines = Range(«B5»).Value  
       .Display3DShading = True  
   End With  

     Range(«E2»).Select  
   ActiveCell.FormulaR1C1 = _  
       «=VLOOKUP(R3C9,'[Список студентов.xls]Список групп’!R4C1:R13C2,2)»
       ActiveSheet.Shapes(«Bill»).Select  
   GR = Range(«E2»).Value  
   FRM = «=MAX(‘[Список студентов.xls]» & GR & «‘!R8C1:R38C1)»
   Range(«A5»).Formula = FRM  
   m = 7 + Range(«A5»).Value  
   With Selection  
       .ListFillRange = «‘[Список студентов.xls]» & GR & «‘!$B$8:$B$» & m
       .LinkedCell = «$A$4»  
       .MultiSelect = xlNone  
       .Display3DShading = True  
   End With  
   FRM = «=VLOOKUP(R4C1,'[Список студентов.xls]» & GR & «‘!R4C1:R» & m & «C4,2)»
   Range(«B4»).Select  
   ActiveCell.FormulaR1C1 = FRM  

         FRM = «=VLOOKUP(R4C1,'[Список студентов.xls]» & GR & «‘!R4C1:R» & m & «C4,3)»
   Range(«D4»).Select  
   ActiveCell.FormulaR1C1 = FRM  

         FRM = «=VLOOKUP(R4C1,'[Список студентов.xls]» & GR & «‘!R4C1:R» & m & «C4,4)»
   Range(«F4»).Select  
   ActiveCell.FormulaR1C1 = FRM  

         If ActiveSheet.Name = «Задание» Then  
       Prep = «='[Список студентов.xls]» & GR & «‘!R5C4»
       Range(«I23»).Formula = Prep  
   End If  
End Sub  

  Sub Print_zsm()  
‘  
   N = Range(«A5»)  
   For i = 1 To N  
       Range(«A4»).Value = i  
       Application.Run «‘Комплектование машин по объектам строительства__мг_mod.xls’!GSN»  
       pa = «A1:» & Cells(1, 1)  
       ActiveSheet.PageSetup.PrintArea = pa  
       ActiveSheet.PageSetup.PrintArea = pa  
       With ActiveSheet.PageSetup  
           .LeftMargin = Application.InchesToPoints(0.78740157480315)  
           .RightMargin = Application.InchesToPoints(0.78740157480315)  
           .TopMargin = Application.InchesToPoints(0.78740157480315)  
           .BottomMargin = Application.InchesToPoints(0.78740157480315)  
           .HeaderMargin = Application.InchesToPoints(0.511811023622047)  
           .FooterMargin = Application.InchesToPoints(0.511811023622047)  
           .PrintQuality = 600  
           .CenterHorizontally = True  
           .CenterVertically = True  
           .Orientation = xlLandscape  
           .PaperSize = xlPaperA4  
           .FitToPagesWide = 1  
           .FitToPagesTall = 1  
       End With  
       ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True  
   Next i  
End Sub  
Sub GSN()  
‘  
‘ Макрос1 Макрос  
‘ Макрос записан 18.06.2009 (Владимир Ефимов)  
‘  

  ‘  
   Dim c(8) ‘ массив для значений ядра  
   Dim s(200) ‘ массив для случайных чисел  
   c(1) = 37584381  
   c(2) = 190999663  
   c(3) = 196446317  
   c(4) = 123567149  
   c(5) = 1480745561  
   c(6) = 442596621  
   c(7) = 340029183  
   c(8) = 203022663  

       Range(«F3»).Select  
   ActiveCell.FormulaR1C1 = _  
       «=RIGHT(RC[-2],LEN(RC[-2])-FIND(«»-«»,RC[-2],LEN(RC[-2])-3))»
   nc = Cells(3, 6)  
   If nc > 8 Then nc = 8  
   mn = Len(Cells(4, 2)) & Len(Cells(4, 4)) & Len(Cells(4, 6)) + Cells(4, 1)  
   mnm = mn Mod 2  
   If mnm = 0 Then mn = mn + 1  
   bb = c(nc) * mn  
   mn = Right(bb, 4)  
   For i = 1 To 200  
      bb = c(nc) * mn  
      mn = Right(bb, 4)  
      s(i) = Right(bb, 8) / 100000000  
      ‘Cells(i + 5, 9) = s(i)  
   Next i  
‘  
‘———   конец генератора случайных чисел ———  
‘  
   ni = 10  
   nj = 10  
   For i = 1 To ni  
      For j = 1 To nj  
          k = j + nj * (i — 1)  
          Cells(i + 9, j + 1) = Cells(10, 12) — Cells(10, 13) + 2 * Cells(10, 13) * s(k)  
      Next j  
   Next i  
‘  
‘  ——- заполнили матрицу затрат  
‘  
   If ActiveSheet.Name = «Решение» Then  
       [B56:K65] = 0
       SolverOk SetCell:=»$D$54″, MaxMinVal:=2, ValueOf:=»0″, ByChange:=»$B$56:$K$65″  
       SolverSolve UserFinish:=True  
   End If  
End Sub  

  Sub Main_m()  
   Application.Run «‘Комплектование машин по объектам строительства__мг_mod.xls’!SM_Z»  
   Application.Run «‘Комплектование машин по объектам строительства__мг_mod.xls’!GSN»  
End Sub  

    Первый раз имею дело с макросами.  
Надеюсь то что надо скопировал

  1. 05-28-2014, 12:47 PM


    #1

    salsabreath is offline


    Registered User


    Compile Error: Sub or Function not defined

    Howdy folks — I’d appreciate your help. I’m a rookie, and am receiving the «Compile Error: Sub or Function not defined» when executing my macro. I’m not clear on how VBA projects, modules, subs, macros, and functions….public and private….all relate — even after spending some time online reading definitions — but certain parts work, this part doesn’t. Seems inconsistent. «Execute_Scenario» works, but «Sale_Scenarios» doesn’t. I’m passing arguments into both. I’ve attached my code and screen shots of errors and compile message, but on a high level my flow is the following…

    MODULE4
    Sub Execute_ScenarioResults()Call Execute_Scenario(column)Call Sale_Scenarios(column, row, SaleMonths)
    End Sub

    Sub Execute_Scenario(ByVal column As Integer)Call IRR_Solver(«Assumptions», «Model_IRR», «NPV_for_IRR_Solver»)
    End Sub

    Sub Sale_Scenarios(ByVal column As Integer, ByVal row As Integer, ByVal SaleMonths As Long)Call IRR_Sale_Scenarios
    End Sub

    MODULE1
    Sub IRR_Solver(ByVal Sheet As String, ByVal IRR As String, ByVal NPV As String)
    End Sub

    MODULE3
    Sub IRR_Sale_Scenarios()Call IRR_Solver(Sheet, IRR, NPV)
    End Sub

    Sub or Function Not Defined Issue_2014-05-28.docx

    Last edited by salsabreath; 06-02-2014 at 04:43 PM.

    Reason: Solved! Thanks for the quick help!


  2. 05-28-2014, 12:54 PM


    #2

    Re: Compile Error: Sub or Function not defined

    I really don’t see the point of uploading a word document with VBA code for an Excel workbook … which doesn’t work for you.

    How would you have us test it, diagnose the problem and propose a solution? No workbook, no worksheets, no data, no formulae, no code (in its home environment).

    If you can upload a word document, it would make more sense to upload an Excel workbook.

    Regards, TMS

    Trevor Shuttleworth — Excel Aid

    I dream of a better world where chickens can cross the road without having their motives questioned

    ‘Being unapologetic means never having to say you’re sorry’ John Cooper Clarke


  3. 05-28-2014, 01:21 PM


    #3

    salsabreath is offline


    Registered User


    Re: Compile Error: Sub or Function not defined

    Good points. Attaching the XLS w/ the macros & VBA. The problem I’m having is when executing the «Execute_ScenarioResults» macro on the 2nd worksheet «Scenario Analysis». The procedure blows up when trying to call the «Sale_Scenarios» subroutine.

    Valuation Model_DEV.zip


  4. 05-28-2014, 03:22 PM


    #4

    Re: Compile Error: Sub or Function not defined

    I just changed:

    to:

    That’s as far as I can take it because, stepping through the code, I get a missing Project or Library … which relates to SOLVER.XLAM. I don’t have that installed so I can’t test any further.


  5. 05-28-2014, 04:51 PM


    #5

    salsabreath is offline


    Registered User


    Re: Compile Error: Sub or Function not defined

    TMS, thanks for the help, but I don’t understand your suggestion. I don’t see anywhere in my code where I have «Application.Run Execute_ScenarioResults()» to change. Assuming that you meant to change the «Execute_ScenarioResults» to «Application.Run Execute_ScenarioResults()»…I don’t understand where. I have «Sub Execute_ScenarioResults()» which defines the subroutine…but don’t understand how you’d replace that sub definition with something that sounds like an executable. I also looked at changing the macro assignment on the button, but it wouldn’t let me….I was limited to only using the defined macros. Can you please clarify? FYI, and forgive me if this is basic/common knowledge, but solver is a standard add-in which can be easily toggled on/off via the File->Add-ins menu path.

    Thanks!


  6. 05-28-2014, 05:04 PM


    #6

    Re: Compile Error: Sub or Function not defined

    In the sheet module (Sheet10 — Scenario Analysis), you have:

    Regards, TMS


  7. 05-29-2014, 10:45 AM


    #7

    salsabreath is offline


    Registered User


    Re: Compile Error: Sub or Function not defined

    I found it, and made the change, but no difference. It still gets the same compiler error at the exact same location….at the Sale_Scenarios().


  8. 05-29-2014, 12:51 PM


    #8

    Re: Compile Error: Sub or Function not defined

    Using Solver in a maro you must first set a reference to Solver in the Visual Basic window.

    For Excel 2010/2007 go to «Visual Basic» click «Tools» then click «References» and tick box marked «Solver». If «Solver» not found you must browse for it. For Excel 2010 the file you must select is the «Solver.xlam» file. Normaly found at «C:Program Files(x86)Microsoft OfficeOffice14LibrarySolverSolver.xlam»

    If you got Excel 64 bit then it’s «Program Files» without the «(86)» part and for Excel 2007 it’s «Office12» instead of «Office14»

    Alf


  9. 05-29-2014, 06:18 PM


    #9

    salsabreath is offline


    Registered User


    Re: Compile Error: Sub or Function not defined

    Thanks Alf, but Solver is already checked in the references. In fact, all of the functionality that is in there now was previously working before I re-organized and re-wrote the code. I originally created the macro via a recording so there were some inefficiencies there such as click cell, select it, copy it, go to another sheet, select a cell, paste it…..and then the functionality itself was duplicated 9 times over. But it worked w/o a compile error. This error was introduced after I organized it into subroutines. I bet it has to do with the way that I’ve declare the subroutines, or how I call them, or how I’m passing variables into them. It frustrates me b/c it gets through 50% of my program — which includes calling the «Execute_Scenario» subroutine along with passing a parameter to it…it processes fine, but when it goes to process the Sale_Scenarios subroutine….which is very similar, it craps out. I’d appreciate any help or ideas that you have! Thanks!


  10. 05-30-2014, 06:53 AM


    #10

    Re: Compile Error: Sub or Function not defined

    Will have a look at your uploaded file in post #3 and see if I can spot the problem.

    Alf


  11. 05-31-2014, 03:04 PM


    #11

    Re: Compile Error: Sub or Function not defined

    Excamening the Sub Sale_Scenarios macro I’m a bit puzzled by your range command i.e

    Should that not be

    Aside from that I’ve not seen anything that looks strange to me.

    Alf


  12. 05-31-2014, 03:35 PM


    #12

    Re: Compile Error: Sub or Function not defined

    Entia non sunt multiplicanda sine necessitate


  13. 06-02-2014, 04:34 PM


    #13

    salsabreath is offline


    Registered User


    Re: Compile Error: Sub or Function not defined

    Thanks Alf & shg, that was an issue, and once corrected it let me get a little further. Not sure of what the etiquette is …. whether I’m supposed to close this and open another thread, but it’s crapping out with a «Run Time Error 1004, Application-defined or object-defined error» message at the following section. Do ya’ll see anything wrong with the following (in that same Sale_Scenarios subroutine)?


  14. 06-02-2014, 04:40 PM


    #14

    salsabreath is offline


    Registered User


    Re: Compile Error: Sub or Function not defined

    Wahoooo! As soon as I posted this last issue I saw the error within the post (which I didn’t see in my VBA code after staring at it for an hour+). I forgot an «.Address» after the first «Cells(row,column)» which caused the error. Here was the updated/corrected code which worked.

    Thanks for the help!!!


  15. 06-02-2014, 05:03 PM


    #15

    Re: Compile Error: Sub or Function not defined

    Not sure of what the etiquette is …. whether I’m supposed to close this and open another thread,

    No you still have a problem within the original thread so you don’t have to start another thread unless you feel that a new thread will atract «new» forum members with better ideas. If so you should mark this thread «Solved» before staring a new thread.

    Have tested and got the same problem as you describe. Just looking at the macro it seems to me that wish to copy a range or rather the value to a range named «Result1» and «Result2». If the the copy from and the copy to range are not excatly the same size Excel will throw an error.

    Have you tried testing with copy from i.e.

    Alf

    Ps Thanks for feed back and rep


Понравилась статья? Поделить с друзьями:
  • Excel stdole32 tlb error
  • Excel spill error
  • Excel runtime error 424 object required
  • Excel run time error 5 invalid procedure call or argument
  • Excel ref error