2013-05-08 66 views
1

我目前正在編寫一個函數,動態地編寫一個sql查詢來檢索一些帖子,我遇到了一個小問題。如何刪除字符串中最後一次出現的字符?

僞代碼:

if trim$(sSqlQuery) <> "" then 

    sSqlQuery = "foo foo) foo" 

end if 


if 1 = 1 then 

    sSqlQuery = sSqlQuery & "bar bar bar" 

end if 

該函數返回正確的SQL查詢的大部分時間,但由於此人之前在較早的功能某些情況下,第二如果子句將被觸發。導致奇怪的查詢結果。

我需要做的是找出如何在sSqlQuery中刪除最後一次出現的「)」,然後再將第二組查詢附加到第二個if-子句中的全部查詢中。

在僞我覺得它會是這個樣子:

if 1 = 1 then 

    call removeLastOccurringStringFromString(sSqlQuery, ")") 

    sSqlQuery = sSqlQuery & "bar bar bar" 

end if 

然而,我發現它真的很難得的Right()Left()Mid()功能的把握。

我曾嘗試是這樣的:

nLen = InStrRev(sSqlSokUrval, ")") ' To get the positional value of the last ")" 

之後,我完全失去了。因爲如果我用Mid()對此進行子串處理,我只會得到「)」而沒有別的。

有關如何解決此問題的任何想法和/或提示將受到高度讚賞!謝謝!

回答

4
'Searches subject and removes last (and *only* last) occurence of the findstring 
Function RemoveLastOccurenceOf(subject, findstring) 
    Dim pos 
    'Find last occurence of findstring 
    pos = InstrRev(subject, findstring, -1, vbBinaryCompare) 'use vbTextCompare for case-INsensitive search 

    if pos>0 then 'Found it? 
     'Take left of subject UP UNTIL the point where it was found 
     '...Skip length of findstring 
     '...Add rest of string 
     RemoveLastOccurenceOf = Left(subject, pos - 1) & Mid(subject, pos + len(findstring)) 
    else 'Nope 
     'Return entire subject 
     RemoveLastOccurenceOf = subject 
    end if 
End Function 
+0

謝謝,這工作就像一個魅力! – doge 2013-05-08 09:32:01

+0

當然它:P – RobIII 2013-05-08 09:33:34

相關問題