2014-07-07 90 views
1

嗨,大家好我的職責如下:函數返回奇怪的輸出

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 \ 1E \ 1 \ EC \ FP7 \ GEC \ FP7 \ GENE \ FP7 \ GENERAFP7 \ GENERAL \ P7 \ GENERAL \ MA7 \ GENERAL \ MART \ GENERAL \ MARTA GENERAL \ MARTA LIENERAL \ MARTA LIBINERAL \ MARTA LIBI MERAL \ MARTA LIBI MAXRAL \ MARTA LIBI MAX \ HAL \ MARTA LIB I MAX \ HR \ L \ MARTA LIBI MAX \ HR「

當我調試它時,我看到混亂開始時,得到」\「。

任何人都可以幫助我理解問題嗎? 謝謝!

+2

使用'Mid(str,i,1)'而不是'Mid(str,i,i)' –

+0

OMG,不能更正確!謝謝! –

+0

請「回答問題」,以便我可以將其標記爲已回答。 –

回答

2

使用Mid(str, i, 1)而不是Mid(str, i, i):第三個參數是返回的字符串的長度,所以它應該是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