2015-11-05 86 views
0

我完全不熟悉VBA。我需要寫一個宏來做下面的僞代碼描述。任何對VBA代碼的引用都是從我從Google搜索到的例子中看到的。非常感謝您提供的任何指導。如何在Word中查找文本,在VBA文本之前插入其他值

Dim myText as string; 
Dim myAutoTextFieldValue as string; 
Set myText='Figure'; 
Set myAutoTextFieldValue = 'fignum'; 
    // fignum is a autotext value that will insert a sequence type field 

.Find text which matches this Word expression \[[0-9]*[0-9]*[0-9]\] 
    // this expression works in the Find what function in Word, not strictly regex 

For each 
.InsertBefore (myText + myTextAutoFieldValue); 
    // I'm guessing I'll need a With expression and a Do While. 

編輯:

我現在有以下但我得到「方法或數據成員找不到」當我試圖運行它。

Sub EditFindLoop() 
'find text where the string equals [00:00:00] or numeric sequence as per input mask 
'then insert myText and myAutoTextFieldValue before it 
Dim myText As String 
Dim myAutoTextFieldValue As String 
Dim myFind As String 
myFind = "\[[0-9]*[0-9]*[0-9]\]" 
myAutoTextFieldValue = "fignum" 
myText = "Figure" 
    With ActiveDocument.Content.Find 
     '.Text = myFind 
     '.ClearFormatting 
     .MatchWildcards = True 
     Do While .Execute(findText:=myFind, Forward:=True) = True 
        .InsertBefore myText & myAutoTextFieldValue 
     Loop 
    End With 
End Sub 
+0

堆棧溢出不是一個教學網站,或人們爲你寫代碼的地方。這是一個提問有關您使用的代碼所遇到的特定問題的地方。有些網站鼓勵教學,人們會爲您提供代碼 - 在MSDN上嘗試使用Microsoft Communities(Answers)或Word for Developers。在互聯網搜索中,您會發現TONS代碼示例,用於在Word中執行通配符搜索,並執行操作的「中斷」。但是請注意,您可能甚至不需要任何VBA代碼,因爲Word的REPLACE功能可以完成您要查找的功能。 –

+0

@CindyMeister我確實需要VBA。如果Word的REPLACE函數有我需要的,我不會在這裏問。我並不懶惰,我做了功課測試了我想要做的事情,而不是先訴諸於VBA。 – quicksilverEnquirer

回答

0

這是我自己的問題的答案,如果其他人需要類似的代碼段。

Sub EditFindLoop() 
    Dim myText As String 
    Dim myFind As String 
    Dim x As Integer 
    myFind = "\[[0-9]*[0-9]*[0-9]\]" 
    myText = "Figure " 
    mySpace = ". " 
    x = 1 
    Dim oRange As Word.Range 
    Set oRange = ActiveDocument.Range 

    With oRange.Find 
     .Text = myFind 
     .ClearFormatting 
     .MatchWildcards = True 
     .MatchCase = False 
     .MatchWholeWord = False 

     Do While .Execute = True 
      If .Found Then 
       oRange.InsertBefore (myText & x & mySpace) 
      End If 
      oRange.Start = oRange.End 
      oRange.End = ActiveDocument.Range.End 
      x = x + 1 
     Loop 
    End With 

End Sub 
相關問題