简体   繁体   English

如何在Excel VBA中删除字符串中的第一个逗号

[英]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? 如果我有一个字符串: "foo, bar" baz, test, blah ,如何删除特定的逗号,即不是全部,而是我选择的一个?

with Replace and INSTR it looks like I have not know where the comma is. ReplaceINSTR看起来好像我不知道逗号在哪里。 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: 以这种方式尝试使用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

It works as expected for the sample value you have provided but could require additional adjustments by changing .Pattern for more complicated text. 它可以为您提供的示例值按预期工作,但可能需要通过更改.Pattern进行其他调整, .Pattern获取更复杂的文本。

EDIT If you want to use this solution as an Excel function than use this code: 编辑如果您想将此解决方案用作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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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