2010-11-22 123 views
3

我正在使用此函數來替換字符文檔中訪問的某些字符串。此功能工作得很好VBA中的「with」子句令人討厭的問題

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean) 
    With doc.Content.Find 
     .Text = after 
     .Replacement.Text = before 
     .Forward = True 
     .Wrap = wdFindContinue 
     .Format = False 
     .MatchCase = False 
     .MatchWholeWord = True 
     .MatchWildcards = False 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False 
     If replaceall Then 
      .Execute replace:=wdReplaceAll 
     Else 
      .Execute replace:=wdReplaceOne 
    End If 
    End With 
End Sub 

但是...我不知道爲什麼,如果我重寫這樣它停止工作的功能。沒有錯誤或警告,但沒有更換。

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean) 
    doc.Content.Find.Text = after 
    doc.Content.Find.Replacement.Text = before 
    With doc.Content.Find 
     .Forward = True 
     .Wrap = wdFindContinue 
     .Format = False 
     .MatchCase = False 
     .MatchWholeWord = True 
     .MatchWildcards = False 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False 
     If replaceall Then 
      .Execute replace:=wdReplaceAll 
     Else 
      .Execute replace:=wdReplaceOne 
     End If 
    End With 
End Sub 

有人可以解釋這兩個片段之間的區別是什麼或爲什麼第二個不工作propertyly? 謝謝!

回答

7

Find屬性返回每次調用它的時間查找對象。因此,在你第二代碼片段你

  1. 創建查找對象,並設置其Text屬性
  2. 創建一個新的查找對象,並設置其屬性Replacement.Text
  3. 創建第三查找對象和設置其他一些屬性和執行

最後執行查找對象沒有它的Text或Replacement.Text屬性集。如果你想以這種方式使用它,你可以創建一個對象變量,如

Sub reemplazar(doc As Word.Document, after As String, before As String, replaceall As Boolean) 

    Dim fnd As Find 

    Set fnd = doc.Content.Find 

    fnd.Text = after 
    fnd.Replacement.Text = before 
    With fnd 
     .Forward = True 
     .Wrap = wdFindContinue 
     .Format = False 
     .MatchCase = False 
     .MatchWholeWord = True 
     .MatchWildcards = False 
     .MatchSoundsLike = False 
     .MatchAllWordForms = False 
     If replaceall Then 
      .Execute Replace:=wdReplaceAll 
     Else 
      .Execute Replace:=wdReplaceOne 
     End If 
    End With 
End Sub 
+0

正確的答案 - 原因和答案代碼。您可以並且應該清楚地說明您正在枚舉第二個代碼段的問題。 – jpinto3912 2010-11-22 22:01:51

1

這是您的代碼的真正切割和粘貼?這兩個應該一致地工作。你確定沒有其他事情像奇數行結尾一樣?

(我注意到在第一個例子你End If不正確縮進,但我懷疑這是什麼做的話)

+0

是的,這實際上是我的代碼的副本。我也認爲這兩個函數應該是一致的......可以肯定的是,WITH子句只是語法糖。這是我的問題和我頭痛的原因。謝謝! – Jonathan 2010-11-22 18:32:22