【问题标题】:Take a text from a cell in excel and add to a bookmark in word从excel中的单元格中获取文本并添加到word中的书签
【发布时间】:2022-07-06 02:16:46
【问题描述】:

我正在尝试做一些看起来很简单的事情,获取工作表中单元格 A1 中的值,并将其放入文档中的某个位置(使用书签)。

我可以打开我的文档,但我试图将单元格设置为变量(字符串),并在书签中/之后打印它

我在大约 7 年前就有了一些编码经验,所以如果能以最简单的方式解释,那就太理想了

单元格是 A1 书签名称为“地球” 细胞中的价值就是世界

这是我目前的代码

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 

我不知道这是否有意义,就像我说我的编码经验是 7 年前的 A Level Computer Science 一样

【问题讨论】:

标签: excel vba word bookmarks


【解决方案1】:

像这样:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-13
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多