You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改GetMaxString代码以实现GetMinString功能?

如何修改VBA函数获取最小字符串?

原函数用来获取字符串数组的最大值,但直接把比较符号从<改成>后没法得到最小值,问题出在函数的初始值是空字符串。

在VBA的字符串比较规则里,空字符串""会被判定为小于任何非空字符串,所以当你写If GetMaxString > strValues(i)时,"" > 任意非空串永远是False,循环里根本不会更新函数的返回值,最后得到的还是空串。

正确的修改方法是先给函数返回值赋初始值(数组的第一个元素),再从第二个元素开始比较:

Public Function GetMinString(ByRef strValues() As String) As String
    Dim i As Long
    ' 先初始化最小值为数组第一个元素
    GetMinString = strValues(LBound(strValues))
    ' 从第二个元素开始循环比较
    For i = LBound(strValues) + 1 To UBound(strValues)
        If GetMinString > strValues(i) Then GetMinString = strValues(i)
    Next i
End Function

如果数组可能为空,建议加个判断避免报错:

Public Function GetMinString(ByRef strValues() As String) As String
    Dim i As Long
    ' 判断数组是否为空
    If LBound(strValues) > UBound(strValues) Then
        GetMinString = ""
        Exit Function
    End If
    ' 初始化最小值为数组第一个元素
    GetMinString = strValues(LBound(strValues))
    For i = LBound(strValues) + 1 To UBound(strValues)
        If GetMinString > strValues(i) Then GetMinString = strValues(i)
    Next i
End Function

内容的提问来源于stack exchange,提问作者Peter DesRosier

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 23:20:39