【问题标题】:How to select part of a text field using ms word macros如何使用 ms word 宏选择文本字段的一部分
【发布时间】:2017-11-20 06:34:55
【问题描述】:

我正在尝试为 Xero 构建模板发票。 Xero 在您的 MS Word 模板中查找特定字段,并以您的给定格式输入分配给该 文本字段 名称的变量。在 word 中,您可以切换字段代码以仅查看字段名称:

«InvoiceNumber»

或带有格式的名称:

{ MERGEFIELD InvoiceNumber \* MERGEFORMAT}

这会输出:INV1234 成功进入模板。现在我需要做的是只输出最后 4 个字符。

This post 似乎暗示它必须使用 VBA 完成。我将 Visual Basic 放在一起,这就是我遇到麻烦的地方:

Sub InvoiceNumber()
    Dim MyInv As FormFields
        Set MyInv = ActiveDocument.FormFields
        If MyInv("Text1").Result = "InvoiceNumber" Then
            MyInv("Text1").CheckBox.Value = Right(MyInv("Text1"), 4)
        End If
End Sub

这会返回

错误 5941:选择的请求成员不存在

我是 VB 宏的初学者,我做错了什么,我应该如何尝试调用 InvoiceNumber 字段?

【问题讨论】:

    标签: vba ms-word textfield


    【解决方案1】:

    请尝试以下解决方案:

    Sub InvoiceNumber()
            Dim MyInv As Field
            Set MyInv = GetFieldByName("InvoiceNumber")
    
            If Not MyInv Is Nothing Then
                'do something with field result...
                'here... debug to Immediate window
                Debug.Print Right(MyInv.Result, 4)
            End If
    End Sub
    
    Function GetFieldByName(fName As String) As Field
    
        Dim F As Field
        For Each F In ActiveDocument.Fields
            'if not working try with (1) istead of (2) in line below
            If Split(Replace(F.Code, "  ", " "), " ")(2) = fName Then
                Set GetFieldByName = F
                Exit Function
            End If
        Next F
        Set GetFieldByName = Nothing
    End Function
    

    【讨论】:

    • 宏运行良好,修复了我的错误,通常它会输出我所要求的内容,不幸的是,Xero 中的模板阅读器无法与之通信。所以我需要找到另一种方式(可能在 Xero API 中)实现这一目标
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2015-08-27
    • 2014-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多