簡體   English   中英

Excel VBA Function 修剪字符串右側(重復)

[英]Excel VBA Function to Trim Right of String (Repeatedly)

所以,這不應該這么難,但很明顯,我離開 VBA 的時間已經削弱了我的技能。

function 應該采用兩個 arguments,一個字符串 (s) 和一個后綴 (x) 來刪除(直到它不再用作 s 中的后綴......)。

Function RightRemoveRecursive(ByVal s As String, ByVal x As String) As String
    Dim t As String
    t = s
    Do While (Mid(t, Len(t) - Len(x) + 1, Len(x)) = x)
        t = Mid(t, 1, Len(t) - Len(x))
    Loop
    RightRemoveRecursive = t
End Function

在 VBA 調試器中,我看到“t”的值變成了我想要返回的值。 但是,當 Do While... 循環完成(而測試失敗)時,代碼永遠不會執行 function 返回值(名稱)行代碼... 在分配給 Function 的分配上設置斷點名稱永遠不會“中斷”那行...示例:s =“01.00.00.00.00.00.00”和x =“.00”... t應該是“01”

我很困惑。

謝謝你的幫助!

Len(t) - Len(x) + 1在中間返回0到第一個標准。 它不喜歡那樣。 如果值更低,請改為使用Application.Max返回 1:

Function RightRemoveRecursive(ByVal s As String, ByVal x As String) As String
    Dim t As String
    t = s
    Do While (Mid(t, Application.Max(Len(t) - Len(x) + 1, 1), Len(x)) = x)
        t = Mid(t, 1, Len(t) - Len(x))
    Loop
    RightRemoveRecursive = t
End Function

在此處輸入圖像描述

只是為了藝術的緣故,斯科特的有效答案的后期替代品展示了字符串輸入的標記化:

Function RightRepl(ByVal s As String, srch As String)
'a) split into tokens (preserving possible blanks)
    Dim tokens: tokens = Split(Replace(s, " ", "|"), srch)
'b) join tokens trimming right hand blanks
    s = Trim(Join(tokens))
'c) restore original blanks (as well as possible intermediate srch elements)
    RightRepl = Replace(Replace(s, " ", srch), "|", " ")
End Function

請注意,function 在修剪連接之前保留原始空白(以及可能的中間“.00”元素)。

示例調用

Sub ExampleCall()
    Dim s    As String: s = "01.00.00.00.00.00.00.00"
    Dim srch As String: srch = ".00"
    Debug.Print vbTab & s & vbNewLine & _
       "==> " & vbTab & RightRepl(s, srch)   ' << helper function
End Sub

結果在 VB 編輯器的立即 window

    01.00.00.00.00.00.00.00
==> 01

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM