Compile error expected sub function or property

I am getting a compile error in Excel VBA which says Expected Sub, Function or Property. The function I am using is given below which is trying to copy the rate function in Excel. Thanks for your h...

I am getting a compile error in Excel VBA which says Expected Sub, Function or Property. The function I am using is given below which is trying to copy the rate function in Excel.
Thanks for your help.

Function rate_m(nper As Double, pmt As Double, pv As Double, fv As Double, types As Double, guess As Double) As Variant
    Dim y, y0, y1, x0, x1, f, i As Double
    Dim FINANCIAL_MAX_ITERATIONS As Double
    Dim FINANCIAL_PRECISION As Double

    If IsNull(guess) Then guess = 0.01
    If IsNull(fv) Then fv = 0   
    If IsNull(types) Then types = 0

    FINANCIAL_MAX_ITERATIONS = 128 'Bet accuracy with 128
    FINANCIAL_PRECISION = 0.0000001 '1.0e-8

    y , y0, y1, x0, x1, f, i = 0
    rate_m = guess

    If Abs(rate_m) < FINANCIAL_PRECISION Then
        y = pv * (1 + nper * rate_m) + pmt * (1 + rate_m * types) * nper + fv
    Else
        f = Exp(nper * Log(1 + rate_m))
        y = pv * f + pmt * (1 / rate_m + types) * (f - 1) + fv

        y0 = pv + pmt * nper + fv
        y1 = pv * f + pmt * (1 / rate_m + types) * (f - 1) + fv
    End If

    'find root by Newton secant method
    i , x0 = 0
    x1 = rate_m

    While Abs(y0 - y1) > FINANCIAL_PRECISION & i < FINANCIAL_MAX_ITERATIONS
        rate_m = (y1 * x0 - y0 * x1) / (y1 - y0)
        x0 = x1
        x1 = rate_m

        If Abs(rate_m) < FINANCIAL_PRECISION Then
            y = pv * (1 + nper * rate_m) + pmt * (1 + rate_m * types) * nper + fv
        Else
            f = Exp(nper * Log(1 + rate_m))
            y = pv * f + pmt * (1 / rate_m + types) * (f - 1) + fv
        End If

        y0 = y1
        y1 = y
        i = i + 1
    Wend
End Function

  1. 08-29-2005, 09:05 PM


    #1

    Compile error: Expected Sub, Function, or Property

    I don’t program very much so I am prone to silly errors. I just can’t
    get the following subprocedure to call my funtion. I keep getting the
    «Compile error: Expected Sub, Function, or Property» error message when
    the program tries to execute the line:
    CheckNumber = CorrectABNDigits(CellContents).
    When stepping through the code, the function is highlighted after the
    call, so it seems to recognise it, but then it won’t step into it,
    giving me the same error message over and over. What am I doing wrong?
    Why isn’t my function a function even if the debugger jumps to it?

    I am trying to get the program to read the contents of a cell into
    «CellContents», pass this string to the function «Function
    CorrectABNDigits(CellContents As String) As Boolean», and then do some
    checks on the string. But my sub won’t call my function.

    Any further comments / criticisms regarding the way I have programmed
    this are welcome!

    Sub ABNtidy()
    Dim CellContents As String
    Dim CheckNumber As Boolean

    Range(«E2»).Select
    CellContents = Selection.Value
    CheckNumber = CorrectABNDigits(CellContents)
    MsgBox (CheckNumber)
    End Sub

    Function CorrectABNDigits(CellContents As String) As Boolean
    Dim MyCheck As Boolean

    If Len(CellContents) = 11 Then MyCheck ’11 characters in cell
    CorrectABNDigits = MyCheck
    End Function


  2. 08-29-2005, 10:05 PM


    #2

    Re: Compile error: Expected Sub, Function, or Property

    This line looks like it’s missing something:

    If Len(CellContents) = 11 Then MyCheck ’11 characters in cell

    maybe:

    If Len(CellContents) = 11 Then MyCheck = True ’11 characters in cell

    ?????

    Cloudfall wrote:


    >
    > I don’t program very much so I am prone to silly errors. I just can’t
    > get the following subprocedure to call my funtion. I keep getting the
    > «Compile error: Expected Sub, Function, or Property» error message when
    > the program tries to execute the line:
    > CheckNumber = CorrectABNDigits(CellContents).
    > When stepping through the code, the function is highlighted after the
    > call, so it seems to recognise it, but then it won’t step into it,
    > giving me the same error message over and over. What am I doing wrong?
    > Why isn’t my function a function even if the debugger jumps to it?
    >
    > I am trying to get the program to read the contents of a cell into
    > «CellContents», pass this string to the function «Function
    > CorrectABNDigits(CellContents As String) As Boolean», and then do some
    > checks on the string. But my sub won’t call my function.
    >
    > Any further comments / criticisms regarding the way I have programmed
    > this are welcome!
    >
    > Sub ABNtidy()
    > Dim CellContents As String
    > Dim CheckNumber As Boolean
    >
    > Range(«E2»).Select
    > CellContents = Selection.Value
    > CheckNumber = CorrectABNDigits(CellContents)
    > MsgBox (CheckNumber)
    > End Sub
    >
    > Function CorrectABNDigits(CellContents As String) As Boolean
    > Dim MyCheck As Boolean
    >
    > If Len(CellContents) = 11 Then MyCheck ’11 characters in cell
    > CorrectABNDigits = MyCheck
    > End Function

    Dave Peterson


  3. 08-29-2005, 11:11 PM


    #3

    Cloudfall

    in this line of code
    If Len(CellContents) = 11 Then MyCheck

    Excel appears to be treating MyCheck as sub routine or a function.

    Try

    If Len(CellContents) = 11 Then MyCheck = True

    Another way to write your code is

    Sub ABNtidy()
    Dim CheckNumber As Boolean

    CheckNumber = CorrectABNDigits(Range(«a2»).Value)
    MsgBox (CheckNumber)
    End Sub

    Function CorrectABNDigits(CellContents As String) As Boolean
    Dim MyCheck As Boolean

    If Len(CellContents) = 11 Then MyCheck = True ’11 characters in cell
    CorrectABNDigits = MyCheck
    End Function


  4. 08-30-2005, 01:05 AM


    #4

    Re: Compile error: Expected Sub, Function, or Property

    To Dave Peterson and mudraker:

    You were both spot on. For some reason I had thought that a declared
    boolean variable would simply default to true in an «if…then»
    statement if the «if» part was correct (I thought I remembered learning
    this somewhere). I won’t make this mistake again. I never expected an
    error of this kind to generate the «Compile error: Expected Sub,
    Function, or Property» error message. I thought it was talking about
    «Function CorrectABNDigits(CellContents As String) As Boolean» when it
    was talking about MyCheck (as mudraker helpfully pointed out above).
    That’s why the debugger did indeed jump to «Function
    CorrectABNDigits(CellContents As String) As Boolean» but refused to
    execute any of its code.

    And mudraker’s suggestion regarding «CheckNumber =3D
    CorrectABNDigits(Range(«a2″).V=ADalue) » is far more elegant. I wasn’t
    aware you could do this. I don’t know Excel VBA very well so I am
    finding this group phenomenally helpful (including past answers to
    other peoples’ questions). I am now faced with a major programming
    chore and I am trying to use good habits from the very beginning.

    Thank you for your fast responses and I wish you both all the very
    best.


Function GetPingResult(Host)
 
   Dim objPing As Object
   Dim objStatus As Object
   Dim strResult As String
 
   Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}"). _
       ExecQuery("Select * from Win32_PingStatus Where Address = '" & Host & "'")
 
   For Each objStatus In objPing
      Select Case objStatus.StatusCode
         Case 0: strResult = "Connected"
         Case 11001: strResult = "Buffer too small"
         Case 11002: strResult = "Destination net unreachable"
         Case 11003: strResult = "Destination host unreachable"
         Case 11004: strResult = "Destination protocol unreachable"
         Case 11005: strResult = "Destination port unreachable"
         Case 11006: strResult = "No resources"
         Case 11007: strResult = "Bad option"
         Case 11008: strResult = "Hardware error"
         Case 11009: strResult = "Packet too big"
         Case 11010: strResult = "Request timed out"
         Case 11011: strResult = "Bad request"
         Case 11012: strResult = "Bad route"
         Case 11013: strResult = "Time-To-Live (TTL) expired transit"
         Case 11014: strResult = "Time-To-Live (TTL) expired reassembly"
         Case 11015: strResult = "Parameter problem"
         Case 11016: strResult = "Source quench"
         Case 11017: strResult = "Option too big"
         Case 11018: strResult = "Bad destination"
         Case 11032: strResult = "Negotiating IPSEC"
         Case 11050: strResult = "General failure"
         Case Else: strResult = "Unknown host"
      End Select
      GetPingResult = strResult
   Next
 
   Set objPing = Nothing
 
End Function
 
Sub GetIPStatus()
 
  Dim Cell As Range
  Dim ipRng As Range
  Dim Result As String
  Dim Wks As Worksheet
 
 
Set Wks = Worksheets("Sheet1")
 
Set ipRng = Wks.Range("A2")
Set RngEnd = Wks.Cells(Rows.Count, ipRng.Column).End(xlUp)
Set ipRng = IIf(RngEnd.Row < ipRng.Row, ipRng, Wks.Range(ipRng, RngEnd))
 
  For Each Cell In ipRng
  
    If Cell.Value <> "" Then
        Result = GetPingResult(Cell)
        Cell.Offset(0, 1) = Result
    Else
        Cell.Offset(0, 1) = "No IP specified!"
    End If
    
  Next Cell
 
End Sub
 
Private Sub Clear_Contents_Click()
    Range("A2:B10000").Select
    Selection.ClearContents
    Range("A2").Select
End Sub
 
Private Sub DNSLookup_Click()
    Range("C2:C10000").Select
    Selection.ClearContents
    Range("A2").Select
    
    For x = 2 To Sheets("Sheet1").Range("A10000").End(xlUp).Row
        Dim IPAddy As String
        Dim LookupResult As String
        IPAddy = Sheets("Sheet1").Cells(x, 1).Value
        LookupResult = NSLookup(IPAddy, 0)
        Sheets("Sheet1").Cells(x, 3) = LookupResult
    Next x
End Sub
 
Private Sub Ping_Click()
    Range("B2:C10000").Select
    Selection.ClearContents
    Range("A2").Select
    GetIPStatus
End Sub
 
Public Function NSLookup(lookupVal As String, Optional addressOpt As Integer) As String
 
    Const ADDRESS_LOOKUP = 1
    Const NAME_LOOKUP = 2
    Const AUTO_DETECT = 0
   
    'Skip everything if the field is blank
    If lookupVal <> "" Then
        Dim oFSO As Object, oShell As Object, oTempFile As Object
        Dim sLine As String, sFilename As String
        Dim intFound As Integer
        Set oFSO = CreateObject("Scripting.FileSystemObject")
        Set oShell = CreateObject("Wscript.Shell")
       
        'Handle the addresOpt operand
        'Regular Expressions are used to complete a substring match for an IP Address
        'If an IP Address is found, a DNS Name Lookup will be forced
        If addressOpt = AUTO_DETECT Then
            ipLookup = FindIP(lookupVal)
            If ipLookup = "" Then
                addressOpt = ADDRESS_LOOKUP
            Else
                addressOpt = NAME_LOOKUP
                lookupVal = ipLookup
            End If
        'Do a regular expression substring match for an IP Address
        ElseIf addressOpt = NAME_LOOKUP Then
            lookupVal = FindIP(lookupVal)
        End If
       
        'Run the nslookup command
        sFilename = oFSO.GetTempName
        oShell.Run "cmd /c nslookup " & lookupVal & " > " & sFilename, 0, True
        Set oTempFile = oFSO.OpenTextFile(sFilename, 1)
        Do While oTempFile.AtEndOfStream <> True
           sLine = oTempFile.Readline
            cmdStr = cmdStr & Trim(sLine) & vbCrLf
        Loop
        oTempFile.Close
        oFSO.DeleteFile (sFilename)
       
        'Process the result
        intFound = InStr(1, cmdStr, "Name:", vbTextCompare)
        If intFound = 0 Then
            NSLookup = ""
            Exit Function
        ElseIf intFound > 0 Then
            'TODO: Cleanup with RegEx
            If addressOpt = ADDRESS_LOOKUP Then
                loc1 = InStr(intFound, cmdStr, "Address:", vbTextCompare) + InStr(intFound, cmdStr, "Addresses:", vbTextCompare)
                loc2 = InStr(loc1, cmdStr, vbCrLf, vbTextCompare)
                nameStr = Trim(Mid(cmdStr, loc1 + 8, loc2 - loc1 - 8))
            ElseIf addressOpt = NAME_LOOKUP Then
                loc1 = InStr(intFound, cmdStr, "Name:", vbTextCompare)
                loc2 = InStr(loc1, cmdStr, vbCrLf, vbTextCompare)
                nameStr = Trim(Mid(cmdStr, loc1 + 5, loc2 - loc1 - 5))
            End If
        End If
        NSLookup = nameStr
    Else
        NSLookup = "N/A"
    End If
End Function
 
Public Function FindIP(strTest As String) As String
    Dim RegEx As Object
    Dim valid As Boolean
    Dim Matches As Object
    Dim i As Integer
    Set RegEx = CreateObject("VBScript.RegExp")
       
    RegEx.Pattern = "b(?:d{1,3}.){3}d{1,3}b"
    valid = RegEx.test(strTest)
    If valid Then
        Set Matches = RegEx.Execute(strTest)
        FindIP = Matches(0)
    Else
        FindIP = ""
    End If
End Function


    • #1

    I am relatively new to coding in VBA and keep getting the compile error and cannot figure out why it keeps coming up. Any help on quelling the pop up would be helpful.

    Here is the code where I keep getting the error:

    Sub tax()
    Tester = 0
    livePriceTotal = Cells(lastLiveRow + 1, 2)
    liveTaxTotal = Cells(lastLiveRow + 1, 3)
    silentPriceTotal = Cells(lastSilentRow + 1, 7)
    silentTaxTotal = Cells(lastSilentRow + 1, 8)
    taxRate = Range("G1").Value
    taxExempt = Range("G2")
    taxRateAdj = ((liveTaxTotal + silentTaxTotal) * (100)) / (livePriceTotal + silentPriceTotal - taxExempt)
    Do
    
    
    
    
    If liveTaxTotal + silentTaxTotal = (livePriceTotal + silentPriceTotal - taxExempt) * taxRate Then Tester = 1
        'Cells(1, 8) = taxRateAdj
    If liveTaxTotal + silentTaxTotal <= (livePriceTotal + silentPriceTotal - taxExempt) * taxRate Then Tester = 2
           'ActiveCell(1, 8) = taxRateAdj
    If liveTaxTotal + silentTaxTotal > (livePriceTotal + silentPriceTotal - taxExempt) * taxRate Then Tester = 3
    If Tester = 1 Then taxRate
    If Tester = 2 Then taxRate
    If Tester = 3 Then taxRateAdj
    End Sub

    Display More

    • #2

    Re: Compile Error Expected Sub, Function, or Property

    You have a «Do» statement but no concluding Loop. Either conclude the loop or remove the Do.

    • #3

    Re: Compile Error Expected Sub, Function, or Property

    Removed the «Do» statement.
    Still getting the same error this time the highlighted term is «taxRate»
    Did I not declare taxRate correctly?

    • #4

    Re: Compile Error Expected Sub, Function, or Property

    Hello vtflee,

    Welcome to Ozgrid.

    You should never code without using Option Explicit. It forces you to properly declare your variables.
    Turn on Option Explicit while in the VB Editor: Menu > Tools > Options > check the box for Require Variable Declaration

    Unless you haven’t posted all of your code, none of your variable are declared.
    I don’t see where you have defined «lastliverow» or «lastSilentrow».

    Correct your variable delcarations, then your loop structure, then step through the code.

    Correct/Efficient Uses of Excel Loops

    • #5

    Re: Compile Error Expected Sub, Function, or Property

    Thanks.

    I did declare it in the beginning but did not include it in my previous code. I added it right after the sub tax and ran it again, but still getting the same error and it stops at taxRate again.

    Here’s the code again:

    Sub tax()
    Dim livePriceTotal As Currency
    Dim liveTaxTotal As Currency
    Dim silentPriceTotal As Currency
    Dim silentTaxTotal As Currency
    Dim taxRate As Long
    Dim taxCorrect As Long
    Dim taxExempt As Currency
    Dim taxRateAdj As Long
    
    
    
    
    Tester = 0
    livePriceTotal = Cells(lastLiveRow + 1, 2)
    liveTaxTotal = Cells(lastLiveRow + 1, 3)
    silentPriceTotal = Cells(lastSilentRow + 1, 7)
    silentTaxTotal = Cells(lastSilentRow + 1, 8)
    taxRate = Range("G1").Value
    taxExempt = Range("G2")
    taxRateAdj = ((liveTaxTotal + silentTaxTotal) * (100)) / (livePriceTotal + silentPriceTotal - taxExempt)
    
    
    
    
    If liveTaxTotal + silentTaxTotal = (livePriceTotal + silentPriceTotal - taxExempt) * taxRate Then Tester = 1
        'Cells(1, 8) = taxRateAdj
    If liveTaxTotal + silentTaxTotal <= (livePriceTotal + silentPriceTotal - taxExempt) * taxRate Then Tester = 2
           'ActiveCell(1, 8) = taxRateAdj
    If liveTaxTotal + silentTaxTotal > (livePriceTotal + silentPriceTotal - taxExempt) * taxRate Then Tester = 3
    If Tester = 1 Then taxRate
    If Tester = 2 Then taxRate
    If Tester = 3 Then taxRateAdj
    End Sub

    Display More

    • #6

    Re: Compile Error Expected Sub, Function, or Property

    Where do you define lastLiveRow? What is in G1?

    • #7

    Re: Compile Error Expected Sub, Function, or Property

    G1 is a tax rate. That value is being pulled from another spreadsheet. I used a vlookup function in the G1 cell.

    • #8

    Re: Compile Error Expected Sub, Function, or Property

    Post a workbook.

    • #9

    Re: Compile Error Expected Sub, Function, or Property

    The other workbook where the tax rates are being pulled is too big to post. Hope that’s not an issue.

    • #10

    Re: Compile Error Expected Sub, Function, or Property

    Hard to tell but if you declare something as Long it covers integers so if you have something 0.08 you need to declare as Double. Somewhat mystified by the error message you were getting though. I get an overflow error on the taxrateadj line.

    • #11

    Re: Compile Error Expected Sub, Function, or Property

    Yes. Another one of the many problems I am having. I changed taxRate to double, but still getting the same error. Right now I am only debugging the sub tax section. Would I have to fix the overflow problem first?

    • #12

    Re: Compile Error Expected Sub, Function, or Property

    I don’t understand why you are getting that error, that is not related to overflow afaik (that is because division by zero, but that may only be because of the lack of links when I ran it). Are you running exactly the same code? Have you stepped through the code using F8?

  • Home
  • Forum
  • Access Forums
  • Access
  • compile error: expected sub, function or property

  1. compile error: expected sub, function or property

    I have been researchin this issue all morning.

    I am getting this error on some code I’m trying to run:

    Compile error: expected sub, function or property

    What does the error message mean?

    It highlights a field I am refrencing but the field name is correct?

    This is the code and I have typed in red the part the error refers to:

    Sub DriversAvailable2()
    Dim mydb As Database
    Dim myset As Recordset

    Dim strList As String
    Set mydv = CurrentDb()
    Set myset = mydb.OpenRecordset(«qryDriversAvailable»)
    strList = «This is a list of available drivers: » & vbCrLf
    myset.MoveFirst
    Do While Not myset.EOF
    strList -strList & myset![FullName] & vbCrLf
    myset.MoveNext

    Loop
    MsgBox strList
    End Sub

    Thank you for any help and direction in advance!!!!


  2. You’ve got a minus sign rather than an equals sign. Try:

    strList

    = strList & myset![FullName] & vbCrLf


  3. Hi randoman,

    Eeek thanks for that!!!

    The error message is still coming up though.

    Any other ideas? Please help!!!!!


  4. Well, according to your text above, you have another type-o but I wouldn’t expect a compile error on the line you highlighted:

    Dim mydb As Database
    Set mydv = CurrentDb() ‘<— Should be mydb

    I would expect an ‘object not set’ error on the line

    Set myset = mydb.OpenRecordset(«qryDriversAvailable»)


  5. Hi again!

    This is really embarasing hey.

    I have fixed that type-o and I am still getting the error.

    Actually I did get an error 3601 for a change for a moment and then it went back to the usual compile error.

    Continuing to research and I can’t find anything to help. Feeling really deflated.

    Please help!!!!


  6. The only other thing that I can think of is to explicitly refer to the Value property of the recordset field such as

    strList

    = strList & myset![FullName].Value & vbCrLf

    I use recordsets all the time and usually don’t explicitly refer to the Value property unless I’m working with collections. However, I do explicitly declare the DAO library. For example:

    Dim mydb As DAO.Database
    Dim myset As DAO.Recordset

    Depending on your references and the order in which they appear, you could be implicitly referencing the ADO library. Just to be clear, you get the error when the code runs and the same element is highlighted as you describe in your original post?


  7. Thanks for replying again!!!

    Do you mean the MS DAO 3.6 object library?

    I tried to check this earlier and move it up and I got a DLL error message.

    I know I have stated that I am working in Access 2007 but it is actually 2010. I don’t know why but on the data base it shows 2007 up the top but the properties of access show 2010.

    Anyway I did some research on the DLL error message and came out with the DAO was not neccessary because Access 14. does what the DAO does?

    I’m so confused and really appreciate you looking at this.

    I will also try your other suggestion-Thanks so much!


Please reply to this thread with any new information or opinions.

Similar Threads

  1. Replies: 6

    Last Post: 09-28-2011, 09:20 PM

  2. Replies: 1

    Last Post: 09-19-2011, 10:25 AM

  3. Replies: 7

    Last Post: 04-22-2011, 10:15 AM

  4. Replies: 8

    Last Post: 01-19-2011, 04:48 AM

  5. Replies: 5

    Last Post: 07-29-2010, 10:12 AM


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules

Compile Error Expecting Sub, Function or Property

(OP)

10 Feb 15 23:05

Hi All,

This one has been driving me insane over the past few days. I have searched quite a bit but nothing of concrete leads me to a resolution

I get the Compile Error, expecting Sub, Fucntion or Property. I am relatively new to VBA

I would very much appreciate any help on this.

With thanks…..

Here is my code

Dim dbs As DAO.Database
Dim rst0 As DAO.Recordset
Dim rst2 As DAO.Recordset

Dim Plant1 As String
Dim TotalCOGS As Integer
Dim TotalPlantCOGS As Integer
Dim stDocName As String

DoCmd.SetWarnings False
‘DoCmd.SetWarnings True

Plant1 = «»
TotalCOGS = 0
TotalPlantCOGS = 0

‘Action First Query
DoCmd.OpenQuery («MAT COGS — SKU»)

Set rst0 = CurrentDb.OpenRecordset(«tblMATCOGS-SKU», dbOpenDynaset)
Plant1 = «AU10»
setvalueA (Plant1) <— I get the error on this.

—Rest of Code….

—— FUNCTION HERE
Option Compare Database

Public strName As String
Public strnameA As String
Public strnameB As String

Function setvalueA(strA As String)
strnameA = strA
End Function
Function SetValueB(strB As String)
strnameB = strB
End Function
Function GetValueA()
GetValueA = strnameA
End Function
Function GetValueB()
GetValueB = strnameB
End Function

Понравилась статья? Поделить с друзьями:
  • Compile error expected array vba
  • Compile error else without if vba
  • Compile error duplicate declaration in current scope
  • Compile error dayz что делать
  • Compile error dayz как исправить