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

时间:2017-08-29 20:20:05

标签: vba ms-word word-vba

您好我正在尝试从Excel工作表中复制单元格并填充word文档。我想将excel单元格中的文本复制到word文档中的特定位置。我能够将excel单元格中的文本存储在字符串中,但不知道如何将其存储在我在word doc中提到的单词占位符或书签中。这就是我到目前为止所做的:

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

ë

Tmp正在存储来自excel的值,但是我无法在我的word文档的占位符中替换和打印它,或者如果在word doc的特定位置有任何其他方式打印Tmp字符串也会有效。我也没有在我的代码中声明任何占位符,我不确定我是否应该这样做。我在word文档中创建了占位符,称为“Placeholder1”。我正在使用VBA字来编码。

有关完整代码,请参阅: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

2 个答案:

答案 0 :(得分:0)

这是Word中的代码,用于在书签

中插入文本
    ActiveDocument.Bookmarks("Placeholder1").Range = "abc123"

答案 1 :(得分:0)

这应该会帮助你。

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

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