繁体   English   中英

访问另一个Word文档TextBox

[英]Accessing another word document TextBox

在我的单词“sheet”中,我有一个CommandButton ,当点击它时,会触发代码的某一部分,它基本上是关于打开第二个word文档并将当前文档Document1 )中的一些信息插入第二个( Document2TextBox

我有一个包含一个word文档中文本的String变量(ei Document1 )。 我正在打开第二份文件(ei Document2 )。 然后,我需要从Document2到达一个特定的TextBox ,并在其中插入我已经拥有的一个String变量的值。

话虽这么说,我无法访问第二个文档( Document2 ),因为我总是得到“4160错误”,文件名的结果不正确。

因此,如何访问我的第二个文档( Document2TextBox并将其插入到我已有的特定值中?

我的代码如下(简化为一个变量,因为它对每个变量都相同):


Private Sub btn1_Click()
    Dim strFile As String
    Dim WordApp As New Word.Application
    Dim WordDoc As Word.Document
    Dim name As String

    strFile = "C:\Users\WhateverUser\Desktop\WhateverFolder\Document2.docx"

    name= txtBoxName.Text
    'This comes from the first document (Document1) which is correct.

    ' Opening another Word document (Document2)
    Set WordDoc = WordApp.Documents.Open(strFile)
    WordApp.Visible = True

    'Here is the problem
    'Trying to access the Document2 TextBox (txtBoxNameDoc2) with various ways but I always get the Incorrect File Name Error

    'First I tried
    Documents("Document2.docx").Bookmarks("txtBoxNameDoc2").Range.Text = name
    'Then I tried

    Documents("Document2.docx").txtBoxNameDoc2.Text = name
    'And after those, I went looking on internet and tried what I could find but none did work.

End Sub

我可以推测上面提供的编码中的一些错误,但是如果这行没有返回错误:

Set WordDoc = WordApp.Documents.Open(strFile)
WordApp.Visible = True

那你应该能做到:

WordDoc.Bookmarks(txtBoxNameDoc2).Range.Text = name

这是因为您已经打开了“Document2.docx” 而且您已将其专门分配给WordDoc对象变量。 因为您已经这样做了,所以您不需要像在原始代码中那样从Documents集合中显式引用它。

注意:这假设txtBoxNameDoc2是标识WordDoc文档中书签的有效字符串。 如果它应该被解释为文字字符串(即,它是书签的实际名称 ,那么您需要使用引号来限定它,例如:

WordDoc.Bookmarks("txtBoxNameDoc2").Range.Text = name

如果这继续引发错误,则指定的书签不存在。

可以将一个书签分配给一个TextBox对象。 书签不会“自动”存在于文档中,因此首先您必须确保存在这样的书签。 您可以查看这些并通过功能区分配它们(如果它们不存在)。

除非您创建书签,否则书签不存在。 您假设对象的名称也可以引用书签,虽然它可以 ,但首先您需要创建书签并为其指定要引用它的名称。

暂无
暂无

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

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