使用VBA更新Microsoft Word中的文本框

时间:2017-02-17 14:34:48

标签: vb.net ms-word textbox word-vba

我在使用VBA OnClick更新文本框时遇到问题。我将文本框的属性设置如下:

Name: ContentController_CN
Tag: CC_CN
Modifiers: Friend
LockContentControl: False
LockContents: False
PlaceHolder Text: Click here to enter text.

我尝试用来更新字段的代码块如下:

    Private Sub Btn_Calculate_Click(sender As Object, e As RibbonControlEventArgs) Handles Btn_Calculate.Click
    Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
    Dim doc As Document = Globals.ThisDocument.Application.ActiveDocument
    Dim range As Range = doc.Range
    Dim custName As String = TB_CustName.Text
    Dim shp As Shape
    Dim str As String

    For Each shp In doc.Shapes
        str = "My name is " & shp.Name("ContentController_CN")
        str = str & vbNewLine & "My EditID is " & shp.EditID
        shp.TextFrame.TextRange.Text = str
    Next
End Sub

此应用程序的目标是让用户在UI功能区中输入文本,然后当他们单击按钮时,文档中的文本字段将根据其输入进行更新。

我一直在MSDN上无休止地查看TextFrame对象信息,但无法完成此操作。有人可以修改上面的代码从TB_CustName拉?我最初有一些看起来像这样的代码:

        doc.Shapes("ContentController_CN").TextFrame.TextRange.Text = TB_CustName.Text

运行这行代码时出现以下错误:

System.ArgumentException was unhandled by user code
  HResult=-2147024809
  Message=The index into the specified collection is out of bounds.
  Source=""
  StackTrace:
       at Microsoft.Office.Interop.Word.Shapes.get_Item(Object& Index)
       at azul.gem_ui.Btn_Calculate_Click(Object sender, RibbonControlEventArgs e) in C:\Users\DMI\Desktop\Neo\BlueGem\proj\azul\azul\gem_ui.vb:line 20
       at Microsoft.Office.Tools.Ribbon.RibbonPropertyStorage.ControlActionRaise(IRibbonControl control)
       at Microsoft.Office.Tools.Ribbon.RibbonPropertyStorage.ButtonClickCallback(RibbonComponentImpl component, Object[] args)
       at Microsoft.Office.Tools.Ribbon.RibbonManagerImpl.Invoke(RibbonComponentCallback callback, Object[] args)
       at Microsoft.Office.Tools.Ribbon.RibbonManagerImpl.System.Reflection.IReflect.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters)
  InnerException: 

非常感谢任何帮助。谢谢大家的见解。 :)

0 个答案:

没有答案