简体   繁体   English

如何使用MS Word宏选择文本字段的一部分

[英]How to select part of a text field using ms word macros

I am trying to build template invoices for Xero. 我正在尝试为Xero构建模板发票。 Xero looks for specific fields in your MS Word template and inputs the variable assigned to that text field name in your given format. Xero在MS Word模板中查找特定字段,并以给定格式输入分配给该文本字段名称的变量。 In word you can toggle the field code to view as just the field name: 换句话说,您可以切换域代码以仅作为域名称查看:

«InvoiceNumber»

or the name with format: 或具有以下格式的名称:

{ MERGEFIELD InvoiceNumber \* MERGEFORMAT}

This outputs: INV1234 successfully into the template. 这将输出: INV1234成功进入模板。 Now what I need to do is output just the last 4 characters. 现在我需要做的是仅输出最后4个字符。

This post seems to imply it must be done with a VBA. 这篇文章似乎暗示它必须使用VBA完成。 I put together a macro with Visual Basic in word and this is where I have hit trouble: 我用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

This returns with 这将返回

error 5941: The requested member of the selection does not exist 错误5941:选择的请求成员不存在

I am quite a beginner with VB macros in word, what am I doing wrong and how should I instead be trying to call the InvoiceNumber Field? 我是VB宏的初学者,我做错了什么,我应该如何尝试调用InvoiceNumber字段?

Please try with the following solution: 请尝试以下解决方案:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM