Excel VBA – 如何在列中的每个单词之后插入逗号

我有一个包含多个string的列。 喜欢这个:

+---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+ | | A | B | C | D | E | F | +---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+ | 1 | Early Summer Lawn Application | Service Call | Early Summer Lawn Application | Grub Control | Early Summer Lawn Application | Early Summer Lawn Application | +---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+ 

我的问题是,如何在列中的每个单词之后插入逗号,以最终结束:

 +---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+ | | A | B | C | D | E | F | +---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+ | 1 | Early,Summer,Lawn,Application | Service,Call | Early,Summer,Lawn,Application | Grub,Control | Early,Summer,Lawn,Application | Early Summer Lawn Application | +---+-------------------------------+--------------+-------------------------------+--------------+-------------------------------+-------------------------------+ 

如果结果是在不同的列,它可以失去单词之间的空间,如果结果是在不同的列,我只是不知道如何插入逗号。

这不是一个简单的replace工作吗?

  =replace(A1," ", ",") 

用逗号replace空格。 另一个function是

 =substitute(A1, " ", ",") 

也有效,但替代品有另一个可能派上用场的论据。 它指定要replace的事件。 例如,如果您只想用逗号replace第一个空白区域,但保留其他空格,请尝试以下操作:

 =substitute(A1, " ", ",", 1) 

底线,如果你知道在哪里replace(位置),使用replace,如果你知道要replace(内容),使用替代。 正如你发现的那样,要么只能为狭窄的一类问题工作。

以下示例以编程方式使用逗号代替所有空格:

 Sub example() Dim s1 As String, s2 As String Dim pos As Integer s1 = ActiveSheet.ActiveCell.Value s2 = "" pos = InStr(1, s1, " ") While (pos <> 0) s2 = s2 & Mid(s1, 1, pos - 1) & "," s1 = Mid(s1, pos + 1) pos = InStr(1, s1, " ") Wend s2 = s2 & s1 ActiveSheet.ActiveCell.Value = s2 End Sub