函数返回奇怪的输出

时间:2014-07-07 08:22:32

标签: string excel vba

大家好我的功能如下:

Function strUntilChar(ByVal str As String, ByVal ch As String, Optional ByVal direction As Integer = 1) As String
'returns a subtring of str until specified char not inclusive; for opposite direction the optional parameter= -1
    Dim i As Integer
    Dim count As Integer
    For i = 1 To Len(str)
        strUntilChar = strUntilChar + Mid(str, i, i)
        If Mid(str, i, i) = ch Then
            If direction = 1 Then  'if the direction is normal(not backwards)
                Exit Function
            End If
            strUntilChar = ""
        End If
    Next i

End Function

但是当我用

调用函数时
hrFilePath = "S:\EC\1_EC\FP7\GENERAL\MARTA LIBI MAX\HR\hr.xlsx"
strUntilChar(hrFilePath, "\", -1)

由于某些奇怪的原因,函数返回:

" S:\ ECEC \ 1C \ 1_E \ 1_EC \ 1_EC \ FP_EC \ FP7 \ EC \ FP7 \ GEC \ FP7 \ GENE \ FP7 \ GENERAFP7 \ GENERAL \ P7 \ GENERAL \ MA7 \ GENERAL \ MART \一般\ MARTA GENERAL \ MARTA LIENERAL \ MARTA LIBINERAL \ MARTA LIBI MERAL \ MARTA LIBI MAXRAL \ MARTA LIBI MAX \ HAL \ MARTA LIBI MAX \ HR \ L \ MARTA LIBI MAX \ HR"

当我调试它时,我发现当到达" \"时会发生混乱。

任何人都可以帮我理解这个问题吗? 谢谢!

2 个答案:

答案 0 :(得分:2)

使用Mid(str, i, 1)代替Mid(str, i, i):第三个参数是返回字符串的长度,因此在您的情况下应为1

答案 1 :(得分:0)

下面建议的功能可以满足任一方向并使用Regexp而不是字符解析

Sub Test()
hrFilePath = "S:\EC\1_EC\FP7\GENERAL\MARTA LIBI MAX\HR\hr.xlsx"
MsgBox strUntilChar(hrFilePath, "\", -1)
End Sub

Function strUntilChar(ByVal str As String, ByVal ch As String, Optional ByVal direction As Integer = 1) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
If direction = -1 Then str = StrReverse(str)
With objRegex
.Pattern = "(^.+?)(\" & ch & ".*$)"
strUntilChar = .Replace(str, "$1")
End With
End Function