簡體   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