2015-11-05 61 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 
相关问题