简体   繁体   中英

how to remove the first comma in a string in excel vba

If I have a string: "foo, bar" baz, test, blah , how do I remove a specific comma, ie not all of them, but just one of my choosing?

with Replace and INSTR it looks like I have not know where the comma is. The problem is, I'll only want to remove the comma if it appears between quotation marks.

So, I may want to remove the first comma and I may not.

Put more clearly, if there is a comma between a set of quotation marks, I need to remove it. if not, then there's nothing to do. But, I can't just remove all the commas, as I need the others in the string.

Try with Regexp in this way:

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

It works as expected for the sample value you have provided but could require additional adjustments by changing .Pattern for more complicated text.

EDIT If you want to use this solution as an Excel function than use this code:

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

Ugh. Here's another way

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

With some error-checking for odd number of double quotes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM