这可能只是一个健全性检查,但我得到Sub或Function未定义。我想在工作表上使用它来查找所选范围内最长的字符串。
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
答案 0 :(得分:0)
你是怎么称呼这个功能的? 你是从另一个函数调用它并传入对象searchRange吗? e.g
theString = LongestString("B1:C55")
我还声明了SearchRange的对象类型以及您希望从函数返回的数据类型,例如:
Public Function LongestString(searchRange as Range) as string
同时替换" longLen = Len(searchRange.Cells(0,0).Value)"在你的FOR循环中使用longLen = Len(rcell(0,0).Value),这样你就可以获得当前正在查看的单元格的长度。完成的代码应如下所示(您可能需要编译它才能看到它)
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