Daniel Hernandez
Daniel Hernandez

Reputation: 15

VBA - Sub or Function not Defined

I keep getting a Sub or Function not Defined compile error with my code.

What I am trying to accomplish is to take two item descriptors via input in a cell and then generate a unique alphanumeric serial number to that item and then output it onto the screen as well as save it on another sheet(which admittedly haven't even started to work on).

However, I keep running into the issue of this compile error when trying to get my SerialGenerator function to work.

I am trying to call the function to return the serial number as a string and place into a variable named "serial" so that I can output that onto the screen and then store it on another sheet.

Public Sub GenerateSerialNumber_Click()
    
    Dim itemname As String
    Dim description As String
    Dim serial As String
    
    itemname = Range("c3").Value
    description = Range("e3").Value
    serial = SerialGenerator(finResult)
    
    Range("c21").Value = itemname
    Range("E21").Value = description
    
    
    
    MsgBox "Serial Number Generated."
    
    
End Sub
    
Function SerialGenerator(finResult)
    
    Dim result As String
    Dim myReturn As String
    
    myReturn = Text(RandBetween(0, 9999), "0000") & CHAR(RandBetween(65, 90)) & CHAR(RandBetween(65, 90))
    
    finResult = myReturn
    
    
End Function

Upvotes: 1

Views: 1607

Answers (1)

BigBen
BigBen

Reputation: 50008

  • You are conflating formulas and VBA. Text, RandBetween, and Char are formulas. Their VBA equivalents are Format, WorksheetFunction.RandBetween, and Chr.
  • Much more logical to have SerialGenerator return a value.
Public Function SerialGenerator() As String
   
    With WorksheetFunction
        SerialGenerator = Format$(.RandBetween(0, 9999), "0000") & _
                          Chr$(.RandBetween(65, 90)) & _
                          Chr$(.RandBetween(65, 90))
    End With
    
End Function

And then called...

serial = SerialGenerator

Upvotes: 2

Related Questions