[英]Excel VBA Replace the nth word in a string
我的问题如下:
我有两组字符串。 “单词”用“+”分隔。
字符串 1: A25+F47+w41+r21+h65
字符串 2: 4+7+4+4+2
我有一个文本框,用于标识字符串 1 中的单词“w41”。它是字符串中的第三个单词。 我想替换字符串 2 中的第三个单词,那就是第二个“4”
到目前为止,我所拥有的是:
我正在使用拆分 function 拆分字符串 1,其中有一个“+”:
Result=Split(String1, "+")
然后我用UBound找到w41的position,结果是3。
FindWordPosition = UBound(Result()) + 1
现在我想以同样的方式拆分字符串 2。 但后来我想将字符串 2 中的第三个单词从“4”更改为“3”,然后再将它们放在一起。 结果将是:
字符串 2: 4+7+3+4+2
但我不知道该怎么做:(
一种方法是使用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
编码
Option Explicit
' Results
' For w41:
' A25+F47+w41+r21+h65
' 4+7+3+4+1
' For h65:
' A25+F47+w41+r21+h65
' 4+7+4+4+5
Sub replaceWithIndex()
Const Criteria As String = "w41"
Const str1 As String = "A25+F47+w41+r21+h65"
Const str2 As String = "4+7+4+4+1"
Const Delimiter As String = "+"
Dim Split1() As String: Split1 = Split(str1, Delimiter)
Dim Split2() As String: Split2 = Split(str2, Delimiter)
' Note that an array obtained with 'Split' is always zero-based, while
' the result of 'Application.Match' is always one-based (hence '- 1').
Dim cMatch As Variant: cMatch = Application.Match(Criteria, Split1, 0)
If IsNumeric(cMatch) Then
Split2(cMatch - 1) = cMatch
Debug.Print "Source"
Debug.Print str1
Debug.Print str2
Debug.Print "Result"
Debug.Print Join(Split1, Delimiter)
Debug.Print Join(Split2, Delimiter)
End If
End Sub
如果找到,您可以简单地循环数组并退出:
Public Sub BuildPositions()
Const Criteria As String = "w41"
Const String1 As String = "A25+F47+w41+r21+h65"
Const String2 As String = "4+7+4+4+2"
Const Delimiter As String = "+"
Dim Results() As String
Dim Positions() As String
Dim Index As Integer
Results = Split(String1, Delimiter)
Positions = Split(String2, Delimiter)
For Index = LBound(Results) To UBound(Results)
If Results(Index) = Criteria Then
Exit For
End If
Next
If Index <= UBound(Results) Then
' Result was located.
Positions(Index) = 1 + Index
End If
Debug.Print "Results:", String1
Debug.Print "Positions1:", String2
Debug.Print "Positions2:", Join(Positions, Delimiter)
End Sub
Output:
Results: A25+F47+w41+r21+h65
Positions1: 4+7+4+4+2
Positions2: 4+7+3+4+2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.