VBA - Sub or Function not Defined

眉间皱痕 提交于 2021-02-05 08:51:58

问题


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

回答1:


  • 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


来源:https://stackoverflow.com/questions/64372384/vba-sub-or-function-not-defined

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!