如何在excel vba中删除string中的第一个逗号

如果我有一个string: "foo, bar" baz, test, blah ,我怎么删除一个特定的逗号,即不是所有的人,而只是我select的一个?

与replace和INSTR它看起来像我不知道在哪里逗号。 问题是,我只想删除逗号,如果它出现在引号之间。

所以,我可能要删除第一个逗号,我可能不会。

更清楚地说,如果在一组引号之间有一个逗号,我需要删除它。 如果没有,那么没有什么可做的。 但是,我不能删除所有的逗号,因为我需要string中的其他字符。

用这种方法试用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来获得更多的调整以获得更复杂的文本。

编辑如果您想使用此解决scheme作为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