如果相邻单词以相同的字母开头,则用“/”replace空格,否则用“&”ExcelmacrosVBAreplace

我一直在寻找一个macros,可以遍历一列单元格,并用/replace每个空格,如果相邻的单词以相同的字母开头,则用macrosreplace为&

每个单元格中的3个字母组合的数量可以从空白到超过20+。

 DZP DOP DMM HTP HZW UTT 

 DZP/DOP/DMM&HTP/HZW&UTT 

以DZP DOP开头的每个字母组,应该用D / DOP代替它们的空格,但是DMM和HTP应该是DMM和HTP,每个字的第一个字母是不同的。

我知道我需要比较string的长度和相对位置,然后用If If Else语句迭代该过程。 但是,我只是开始了如果。

此外,我发现很多网站上如何比较细胞,但我还没有find如何在单元格中的单词。

任何帮助都会很棒,特别是如果你能解释怎么写一个比较公式来比较第四个字符。

谢谢你的时间。

如果下一个单词以相同的字母开头,下面的函数将用斜线replace空格。 它只能使用三个字母的文字。

 Function ReplaceSpaces(StrIn As String) As String 'Start at the first space If Len(StrIn) > 3 Then i = 4 Do If Len(StrIn) > i And Mid(StrIn, i, 1) = " " Then If Mid(StrIn, i - 3, 1) = Mid(StrIn, i + 1, 1) Then StrIn = Left(StrIn, i - 1) & "/" & Right(StrIn, Len(StrIn) - i) Else StrIn = Left(StrIn, i - 1) & "&" & Right(StrIn, Len(StrIn) - i) End If End If Debug.Print Chr(34) & Mid(StrIn, i, 1) & Chr(34) i = i + 4 Loop Until i > InStr(1, StrIn, " ") ReplaceSpaces = StrIn End If End Function 

第二个函数可以处理任意长度的单词,包括不同的长度(例如,4个字母的单词后跟3个字母的单词,后面跟着6个字母的单词等)。

 Function BetterReplaceSpaces(StrIn As String) As String Dim lastfirstletter As Integer, i As Integer lastfirstletter = 1 If InStr(1, StrIn, " ") > 0 Then i = InStr(1, StrIn, " ") Do 'If Len(StrIn) > i And Mid(StrIn, i, 1) = " " Then If Mid(StrIn, lastfirstletter, 1) = Mid(StrIn, i + 1, 1) Then StrIn = Left(StrIn, i - 1) & "/" & Right(StrIn, Len(StrIn) - i) Else StrIn = Left(StrIn, i - 1) & "&" & Right(StrIn, Len(StrIn) - i) End If 'End If Debug.Print Chr(34) & Mid(StrIn, i, 1) & Chr(34) lastfirstletter = i + 1 i = InStr(1, StrIn, " ") Loop Until i = 0 BetterReplaceSpaces = StrIn End If End Function