简体   繁体   English

从excel中的单元格中获取文本并添加到word中的书签

[英]Take a text from a cell in excel and add to a bookmark in word

I'm trying to do something that seems so simple: Take the value that is in cell A1 in my worksheet and put it in a document at a certain point (using a bookmark).我正在尝试做一些看起来很简单的事情:将工作表中单元格 A1 中的值放入文档中的某个位置(使用书签)。

I can open my document but I'm trying to make the cell a variable (string), and print it in/after the bookmark.我可以打开我的文档,但我试图使单元格成为变量(字符串),并在书签中/之后打印它。

I have some coding experience from about 7 years ago so if it could be explained in the simplest way possible that'd be ideal.我在大约 7 年前就有了一些编码经验,所以如果可以用最简单的方式来解释,那将是理想的。

The Cell is A1 Name of Bookmark is "Earth" Value in the Cell is World单元格是 A1 书签名称是“地球” 单元格中的值是 World

Here's my code so far到目前为止,这是我的代码

Private Sub CreateWordDoc()
Dim wdApp As Word.Application
Set wdApp = New Word.Application
Dim Cell As String
Range("A1").Value = Cell

With wdApp
.Visible = True
.Activate
.Documents.Add "C:\Users\Desktop\WordBookmarkTest.docx"


wdApp.Activate
End With
End Sub 

I don't know if that makes sense.我不知道这是否有意义。 Like I said, my coding experience is from A Level Computer Science 7 years ago.就像我说的,我的编码经验来自 7 年前的 A Level Computer Science。

Like this:像这样:

Private Sub PopulateWordDoc()
    
    Dim wdApp As Word.Application, doc As Word.Document, ws As Worksheet
    
    Set ws = ThisWorkbook.Worksheets("Values") 'for example
    Set wdApp = New Word.Application
    With wdApp
        .Visible = True
        .Activate
        'get a reference to the opened document
        Set doc = .Documents.Open("C:\Users\Desktop\WordBookmarkTest.docx")
        'populate bookmark "Earth" in `doc`
        AddTextToBookmark doc, "Earth", ws.Range("A1").Value 
    End With
    
End Sub

'Add text `txt` to bookmark `bmName` in document `doc`
'Adding the text deletes the bookmark, so recreate it
Sub AddTextToBookmark(doc As Word.Document, bmName As String, txt)
    Dim rng As Word.Range
    Set rng = doc.Bookmarks(bmName).Range 'get the range of the bookmark
    rng.Text = txt                        'add the text
    doc.Bookmarks.Add bmName, rng         'recreate the bookmark
End Sub

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

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