繁体   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