VBA将标题字段代码从图改为表

时间:2012-06-28 12:41:07

标签: vba field word-vba

我想将所有字幕从一种类型更改为另一种类型。虽然没有意外修改任何其他归档代码。

我提出的过程分为两步:首先更改字段代码中的文本和之前的文本。

即。来自

表{SEQ Table * ARABIC}

图{SEQ图* ARABIC}

我已尝试过手动编辑并更改内部类型,不会自动更改字段外的标签。

要更改文本我使用查找/替换,这可以正常工作:

With Selection.Find
    .Style = ActiveDocument.Styles("Caption")
    .Text = "Figure"
    .Replacement.Text = "Table"
    .Forward = True
    .Wrap = wdFindContinue
End With
Selection.Find.Execute Replace:=wdReplaceAll

要对字段进行编码,我遇到了问题。以下代码将执行更改:

Dim rngTemp As Range
Set rngTemp = ActiveDocument.Fields(1).Code
rngTemp.Text = " SEQ Figure \* ARABIC "
ActiveDocument.Fields(1).Update
然而,我无法确定它只会改变特定类型的字段,即字幕。因为它是代码根据其索引号更改任何字段。

我也很难让它循环使用for / each用i替换数字。我得到一个错误,说“对象不支持这种方法”

任何帮助我们都会非常感谢你。

2 个答案:

答案 0 :(得分:1)

根据上面的链接,下面的代码(未经测试)

怎么样
Dim oField As Field
Dim sCode As String
Dim bFoundOne As String

For Each oField In ActiveDocument.Fields

    If oField.Type = wdFieldSequence Then

        sCode = oField.Code

        If InStr(sCode, "Table") <> 0 Then oField.Code = Replace(sCode, "Table", "Figure")

    End If
Next

答案 1 :(得分:0)

谢谢Scott,这是一个很好的帮助!

只有项目缺失,在代码的替换部分.Text是必需的。然而,你只是替换一个单词而不是整个文本的解决方案更加优雅。

If InStr(sCode, "Table") <> 0 Then oField.Code.**Text** = Replace(sCode, "Table", "Figure")

我试图通过将查找/替换文本输出到字符串中来使代码具有适应性。在那里添加了前面文本的查找/替换代码。并坚持在柜台上进行衡量。

Dim oField As Field
Dim sCode As String
Dim TypeFind As String
Dim TypeReplace As String
Dim bFoundOne As String


bFoundOne = 0

'Swap strings around as required
TypeReplace = "Table"
TypeFind = "Figure"
' = "Equation"

'-- Change Field Code --
For Each oField In ActiveDocument.Fields
    If oField.Type = wdFieldSequence Then
        sCode = oField.Code
        If InStr(sCode, TypeFind) <> 0 Then
            bFoundOne = bFoundOne + 1 'counting how many
            oField.Code.Text = Replace(sCode, TypeFind, TypeReplace)
        End If
    End If
Next

'-- Change preceding text --
With Selection.Find
    .Style = ActiveDocument.Styles("Caption")
    .Text = TypeFind
    .Replacement.Text = TypeReplace
    .Forward = True
    .Wrap = wdFindContinue
End With
Selection.Find.Execute Replace:=wdReplaceAll

MsgBox ("Changed: " & bFoundOne) 'show how many when finished