函数返回奇怪的输出

嗨,我的function如下:

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 

但是,当我调用该function

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

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

“S:\ ECEC \ 1C \ 1_E \ 1EC \ 1_EC \ FP_EC \ FP7 \ EC \ FP7 \ GEC \ FP7 \ GENE \ FP7 \ GENERAFP7 \ GENERAL \ P7 \ GENERAL \ MA7 \ GENERAL \ MART \ GENERAL \ MARTA GENERAL \ MARTA联邦\ MARTA LIBINERAL \ MARTA LIBI MERAL \ MARTA LIBI MAXRAL \ MARTA LIBI MAX \ HAL \ MARTA LIBI MAX \ HR \ L \ MARTA LIBI MAX \ HR“

当我debugging时,我看到乱七八糟的时候开始“\”。

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

使用Mid(str, i, 1)而不是Mid(str, i, i) :第三个参数是返回string的长度,所以应该是1

下面的build议function可以满足任一方向的要求,并使用正则Regexp而不是字符parsing

 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