Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 函数返回奇怪的输出_String_Excel_Vba - Fatal编程技术网

String 函数返回奇怪的输出

String 函数返回奇怪的输出,string,excel,vba,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 A

大家好,我的功能如下:

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\U E\1\U EC\1\U EC\FP\FP7\EC\FP7\GENE\FP7\GENERAFP7\GENERAFP7\GENERAFP7\GENERAFP7\GENERAFP7\GENERAFP7\GENERAF\MA7\GENERAL\MAR7\GENERAF\MA7\GENERAL\MAR\MART\GENERAL\MARTA GENERAL\MARTA LIBI MERAL\MARTA LIBI\HR”

当我调试它时,我看到当到达“\”时开始出现混乱

有人能帮我理解这个问题吗?
谢谢大家!

使用
Mid(str,i,1)
而不是
Mid(str,i,i)
:第三个参数是返回字符串的长度,因此在您的情况下,它应该是
1
,在下面建议的函数中,该函数满足任一方向,并使用
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

Mid(str,i,1)
代替
Mid(str,i,i)
OMG,再正确不过了!非常感谢。请“回答问题”,这样我就可以标记它已回答。