0

我有这个代码,

Dim str As String, Dim replaceStr As String, Dim counter as Integer
str = "I have the number 3"

For counter = 1 To 5
    replaceStr = Replace(str, counter, 99)
Next counter

我希望替换功能能够捕捉到,counter = 3以便将 3 替换为 99。到目前为止,我仍然得到"I have the number 3".

我已经尝试过Replace(str, CStr(counter), 99)并且仍然给我相同的结果。

4

2 回答 2

4

当计数器等于 3 时,您正在执行替换,然后在下一次循环中撤消替换。如果您将代码更改为:

Sub test()
Dim str As String, replaceStr As String, counter As Integer
str = "I have the number 3"

For counter = 1 To 5
    replaceStr = Replace(str, counter, 99)
    Debug.Print replaceStr
Next counter
End Sub

您将看到输出:

I have the number 3
I have the number 3
I have the number 99
I have the number 3
I have the number 3

也许您可以If replaceStr <> str Then Exit ForReplace

于 2018-06-21T19:11:42.887 回答
1

您可以将更改应用于实际字符串,而不是继续引入“新”字符串。

Option Explicit
Sub test()
    Dim str As String, replaceStr As String, counter As Long

    str = "I have the number 3"

    For counter = 1 To 5
           str = Replace(str, counter, 99)
    Next counter

    Debug.Print str
End Sub
于 2018-06-21T19:15:02.783 回答