首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何从word vba向占位符添加文本

如何从word vba向占位符添加文本
EN

Stack Overflow用户
提问于 2017-08-30 04:20:05
回答 2查看 1.4K关注 0票数 1

嗨,我试图从excel工作表中复制单元格并填充word文档。我想将文本从excel单元格复制到word文档中的特定位置。我可以将excel单元格中的文本存储在字符串中,但不确定如何将其存储在word文档中提到的word占位符或书签中。这就是我到目前为止所知道的:

代码语言:javascript
运行
复制
Set ws = xlBook.Worksheets("DIP Main")
    Tmp = ws.Cells(25, "C").Value
    .Text = Tmp
    .Execute Replace:=("Placeholder1")
   ' [Placeholder1] = Tmp.Text
   ' MyDOc.Fields("Placeholder1") = Tmp.Valu

E

Tmp正在存储excel中的值,但是我不能在我的word文档的占位符中替换和打印它,或者如果有任何其他方法可以在word文档的特定位置打印Tmp字符串也可以。我也没有在我的代码中声明任何占位符,我不确定我是否应该这样做。我在word文档中创建了名为"Placeholder1“的占位符。我正在使用VBA word对其进行编码。

有关完整代码,请参阅以下内容:How to copy excel range from a sheet and place it into a specific place it into a specific place in word using word vba

EN

回答 2

Stack Overflow用户

发布于 2017-08-30 04:28:51

这是Word中在书签处插入文本的代码

代码语言:javascript
运行
复制
    ActiveDocument.Bookmarks("Placeholder1").Range = "abc123"
票数 0
EN

Stack Overflow用户

发布于 2017-08-30 10:59:41

这应该会在你的旅途中帮助你。

代码语言:javascript
运行
复制
Sub ExcelToWord()

    ' define all Excel variables you are going to use:
    Dim Wb As Workbook
    Dim Ws As Worksheet
    Dim Cell As Range

    ' define all Word variables you are going to use:
      ' since you are running the code from Excel
      ' you must specify "Word" for each data type
    Dim WdApp As Word.Application
    Dim Doc As Word.Document

    ' define variables which you can use in either application:
      ' (if you aren't sure, define separate ones)
    Dim Tmp As String
    Dim R As Long
    Dim i As Integer

    ' replace this name with the name & path of your own Word document
    Tmp = "E:\PVT Archive\Class 1\1-2017 (Jan 2019)\STO 170317.docm"
    If Dir(Tmp) = "" Then                           ' Check if the file exists
        MsgBox "The file doesn't exist.", _
               vbInformation, "Invalid file or path name"
        Exit Sub
    End If
    Set WdApp = CreateObject("Word.Application")    ' open Word
    WdApp.Visible = True
    Set Doc = WdApp.Documents.Open(Tmp)             ' open the document

    If Not Doc.Bookmarks.Exists("Amark") Then
        MsgBox "The bookmark 'Amark' doesn't exist.", _
               vbInformation, "Can't find bookmark"
        Exit Sub
    End If

    Set Wb = ActiveWorkbook
    Set Ws = Wb.Worksheets("DIP Main")
    Tmp = Ws.Cells(25, "C").Value

    Doc.Bookmarks("Amark").Range.Text = Tmp
End Sub

请注意,书签将被替换为下一个。此后它就不存在了。如果您希望重新使用它,则必须使用代码重新设置它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45947739

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档