带循环的Find.replace并不像我想要的那样工作

时间:2014-05-06 14:07:42

标签: vba word-vba

我想做什么:

  1. 浏览文档并查找word1
  2. 将word1替换为word2
  3. 更改word2(递增)
  4. 1-3直到word1被替换为
  5. 到目前为止我的代码:

    With ThisDocument.Range.Find ' search the Document
        .Text = "RS.0569/14.xxxxx" ' for this text
        .Replacement.Text = nextID ' replace it with an ID ( Start= 0 )
        Do ' loop the .execute part to increment my ID and only touch one ID at a time
            .Execute Replace:=wdReplaceOne ' only replace one word per loop
            nextID = Val(Split(nextID, ".")(2)) + 1 ' this is just ID+1
            nextID = "RS.0569/14.0000" + nextID ' put the ID together
            If Not .Found Then Exit Do ' Loop should stop if everything is replaced
        Loop
    
    End With
    

    问题:循环只运行一次,因为布尔运行不能使用循环 - >我做了#34; Debug.print。"在.execute之前和之后,输出是 - > "假,真,真,假"

    看起来.execute只是切换之前为False的布尔值,但是当循环重复.execute时,它只是将其切换为" false" (因为之前是真的)

    有什么想法吗?我不知道一个解决方法,所以我在这里问......

1 个答案:

答案 0 :(得分:0)

我以前做过一点用词,.Find对象有点棘手,特别是因为我没有做很多Word自动化,但我相信这应该有效:

Dim fnd as Find
nextId = "RS.0569/14.00000"
Set fnd = ThisDocument.Range.Find
fnd.Text = "RS.0569/14.xxxxx"
Do
    nextId = Val(Split(nextId, ".")(2)) + 1
    nextId = "RS.0569/14.0000" & CStr(nextId) ' put the ID together
    fnd.Replacement.Text = nextId ' replace it with an ID ( Start= 0 )
    fnd.Wrap = wdFindContinue
    fnd.Execute Replace:=wdReplaceOne ' only replace one word per loop
Loop Until fnd.Found = False

这是试验&错误,大多数;我认为.Wrap是您继续使用它所需要的。