简体   繁体   中英

Excel Sub or function not defined

This might just be a sanity check, but I'm getting Sub or Function not defined. I want to use this on a worksheet to find the longest string inside a selected range.

Public Function LongestString(searchRange)
    Dim rCell As Range
    Dim rRng As Range

    Dim longText As String
    Dim longLen  As Integer

    longText = searchRange(0, 0).Value
    longLen = Len(searchRange(0, 0).Value)

    For Each rCell In searchRange.Cells
        'Debug.Print rCell.Address, rCell.Value
        If (Len(rCell.Value) > longLen) Then
            longText = rCell(0, 0).Value
            longLen = Len(searchRange.Cells(0, 0).Value)
        End If
    Next rCell

    LongestString = longText
End Function

How are you calling this function? Are you calling it from another function and passing in the object searchRange? eg

theString = LongestString("B1:C55")

I'd also declare the object type of the SearchRange and the data type you want returned from the function as well, eg:

Public Function LongestString(searchRange as Range) as string

Also replace "longLen = Len(searchRange.Cells(0, 0).Value)" in your FOR loop with longLen = Len(rcell(0, 0).Value) so you get the length of the cell you are currently looking at. The finished code should look like this (and you may need to compile it to see it)

Public Function LongestString(searchRange As Range) As String
    Dim rCell As Range
    Dim rRng As Range

    Dim longText As String
    Dim longLen  As Integer

    longText = searchRange(0, 0).Value
    longLen = Len(searchRange(0, 0).Value)

    For Each rCell In searchRange.Cells
        'Debug.Print rCell.Address, rCell.Value
        If (Len(rCell.Value) > longLen) Then
            longText = rCell(0, 0).Value
            longLen = Len(rCell(0, 0).Value)
        End If
    Next rCell

    LongestString = longText
End Function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM