繁体   English   中英

如何从Word VBA向占位符添加文本

[英]How to add text to place holder from word vba

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

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字符串,也可以使用。 我也没有在我的代码中声明任何占位符,我不确定是否应该这样做。 我已经在名为“ Placeholder1”的单词文档中创建了占位符。 我正在使用VBA单词对其进行编码。

有关完整代码,请参考此: 如何从工作表中复制Excel范围并将其放置到特定位置,并使用单词vba将其放置到单词中的特定位置

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

    ActiveDocument.Bookmarks("Placeholder1").Range = "abc123"

这应该可以帮助您。

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

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

暂无
暂无

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

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