簡體   English   中英

如何在Excel VBA中刪除字符串中的第一個逗號

[英]how to remove the first comma in a string in excel vba

如果我有一個字符串: "foo, bar" baz, test, blah ,如何刪除特定的逗號,即不是全部,而是我選擇的一個?

ReplaceINSTR看起來好像我不知道逗號在哪里。 問題是,如果逗號出現在引號之間,我將只希望刪除它。

因此,我可能想刪除第一個逗號,但我可能不想刪除。

更明確地說,如果一組引號之間有逗號,我需要將其刪除。 如果沒有,那就沒事了。 但是,我不能只刪除所有逗號,因為我需要字符串中的其他逗號。

以這種方式嘗試使用Regexp:

Sub foo()
    Dim TXT As String
    TXT = """foo, bar"" baz, test, blah"

    Debug.Print TXT

    Dim objRegExp As Object
    Set objRegExp = CreateObject("vbscript.regexp")

    With objRegExp
        .Global = True  '
        .Pattern = "(""\w+)(,)(\s)(\w+"")"

    Debug.Print .Replace(TXT, "$1$3$4")

    End With


End Sub

它可以為您提供的示例值按預期工作,但可能需要通過更改.Pattern進行其他調整, .Pattern獲取更復雜的文本。

編輯如果您想將此解決方案用作Excel函數,而不是使用以下代碼:

Function RemoveCommaInQuotation(TXT As String)

    Dim objRegExp As Object
    Set objRegExp = CreateObject("vbscript.regexp")

    With objRegExp
        .Global = True 
        .Pattern = "(""\w+)(,)(\s)(\w+"")"

    RemoveCommaInQuotation = .Replace(TXT, "$1$3$4")

    End With


End Function

啊。 這是另一種方式

Public Function foobar(yourStr As String) As String
    Dim parts() As String
    parts = Split(yourStr, Chr(34))
    parts(1) = Replace(parts(1), ",", "")
    foobar = Join(parts, Chr(34))
End Function

通過一些錯誤檢查雙引號的奇數:

Function myremove(mystr As String) As String
    Dim sep As String
    sep = """"
    Dim strspl() As String
    strspl = Split(mystr, sep, -1, vbBinaryCompare)
    Dim imin As Integer, imax As Integer, nstr As Integer, istr As Integer
    imin = LBound(strspl)
    imax = UBound(strspl)
    nstr = imax - imin
    If ((nstr Mod 2) <> 0) Then
      myremove = "Odd number of double quotes"
      Exit Function
    End If
    For istr = imin + 1 To imax Step 2
      strspl(istr) = Replace(strspl(istr), ",", "")
    Next istr
    myremove = Join(strspl(), """")
End Function

暫無
暫無

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

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