首页 > 解决方案 > Excel VBA替换字符串中的第n个单词

问题描述

我的问题如下:

我有两组字符串。“单词”用“+”分隔。

字符串 1:A25+F47+w41+r21+h65

字符串 2:4+7+4+4+2

我有一个文本框,用于标识字符串 1 中的单词“w41”。它是字符串中的第三个单词。我想替换字符串 2 中的第三个单词,那就是第二个“4”</p>

到目前为止,我所拥有的是:

我正在使用 split 函数来拆分字符串 1,其中有一个“+”:

Result=Split(String1, "+")

然后我用 UBound 找到 w41 的位置,结果是 3。

FindWordPosition = UBound(Result()) + 1

现在我想以同样的方式拆分字符串 2。但后来我想将字符串 2 中的第三个单词从“4”更改为“3”,然后再将它们放在一起。结果将是:

字符串 2:4+7+3+4+2

但我不知道该怎么做:(

标签: excelvbastringreplacesplit

解决方案


一种方法是使用ArrayList.

不确定要用什么替换匹配的项目。在下面的代码中,它被替换为与您描述的内容匹配的序列号,但可能不是您真正想要的。

Option Explicit
Sub due()
    Const str1 As String = "A25+F47+w41+r21+h65"
    Const str2 As String = "4+7+4+4+2"
    Const strMatch As String = "w41"
    Dim AL As Object
    Dim v, w, I As Long
    
Set AL = CreateObject("System.Collections.ArrayList")

'put str2 into arrayList
v = Split(str2, "+")
For Each w In v
    AL.Add w
Next w

'Check str1 against matchStr to get positions and act on the item in AL at that position
v = Split(str1, "+")
For I = 0 To UBound(v)
'Note that arrayList index and "Split" array are zero-based
    If strMatch = v(I) Then
        AL.removeat I 'remove item in the same position as the position of the matched item
        AL.Insert I, I + 1 'Insert new item at that same position. Could be anything. I chose I+1 to match what you wrote in your question.
    End If
Next I

Debug.Print Join(AL.toarray, "+")
    
End Sub

=> 4+7+3+4+2


推荐阅读