如何在Word中查找文本,在使用VBA的文本之前插入其他值

时间:2015-11-05 20:34:36

标签: vba ms-word ms-office

我对VBA来说是全新的。我需要编写一个宏来执行以下伪代码描述。任何对VBA代码的引用都来自于我迄今为止从google搜索到的示例。非常感谢您提供的任何指导。

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

1 个答案:

答案 0 :(得分: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