【问题标题】:How to add text to place holder from word vba如何从word vba将文本添加到占位符
【发布时间】:2017-08-30 10:59:41
【问题描述】:

您好,我正在尝试从 Excel 工作表中复制单元格并填充 Word 文档。我想将文本从 excel 单元格复制到 word 文档中的特定位置。我能够将 excel 单元格中的文本存储在字符串中,但不确定如何将其存储在我在 word doc 中提到的 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

e

Tmp 正在存储来自 excel 的值,但我无法在我的 word 文档的占位符中替换和打印它,或者如果有任何其他方法可以在 word doc 的特定位置打印 Tmp 字符串也可以.我也没有在我的代码中声明任何占位符,我不确定我是否应该这样做。我在名为“Placeholder1”的word文档中创建了占位符。我正在使用 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

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

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

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

    【讨论】:

    • 如何使它等于存储在字符串中的值?
    【解决方案2】:

    这应该可以帮助你。

    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
    

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

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 2012-01-03
      • 1970-01-01
      • 1970-01-01
      • 2014-01-08
      • 2013-01-18
      相关资源
      最近更新 更多