【问题标题】:How to copy text into word using excel VBA如何使用excel VBA将文本复制到word
【发布时间】:2020-07-07 01:05:12
【问题描述】:

如何在 Excel 中使用 VBA 将特定文本粘贴到特定位置和标题的 word 中。到目前为止,我可以使用 excel 打开单词,而使用 Excel VBA 可以打开单词。

  Sub Open_word()
    Dim wrdApp As Word.Application
    Dim wrdDoc As Word.Document
    Dim filepath As String

    Set wrdApp = CreateObject("Word.Application")
    wrdApp.Visible = True

    filepath = "https://sharepoint.lamrc.net/cft/edms/Documents/DDS2011.doc"
    Set wrdDoc = wrdApp.Documents.Open(filepath)
    '----------------------Downloads document----------------------


    ActiveDocument.Paragraphs(1).Range.Text = vbCrLf
    ActiveDocument.Paragraphs(1).Range.Text = vbCrLf
    ActiveDocument.Paragraphs(1).Range.Text = vbCrLf
    ActiveDocument.Paragraphs(1).Range.Text = vbCrLf

    wrdApp.ActiveDocument.Content.Delete



    '----------------------Deletes default content----------------------

    Dim strNewFolderName As String
    strNewFolderName = "New Folder " & (Day(Now())) & "_" & Month(Now()) & "_" & Year(Now)
    If Len(Dir("C:\Macro_test\" & strNewFolderName, vbDirectory)) = 0 Then
        MkDir ("C:\Macro_test\" & strNewFolderName)
    End If
    Dim PathName As String
    PathName = ("New Folder " & MonthName(Month(Now())) & " " & Year(Now))

    wrdApp.ActiveDocument.SaveAs "C:\macro_test\" & strNewFolderName & "\" & "test" + ".doc"

    '----------------------save as files----------------------


    Sheets("SCREW").Range("H1:J11").Copy
    wrdApp.Selection.Paste

    Application.CutCopyMode = False

    '------------- pastes the actual content--------------


    Set wrdApp = Nothing

    Set wrdDoc = Nothing

    MsgBox ("DONE")

    '----------------message box---------------

  End Sub'

我可以将内容复制到 word 但无法将其复制到特定位置。

请帮忙。

【问题讨论】:

  • 四处看看。以前也有人问过类似的问题。喜欢here
  • 请具体说明“特定位置”。您的要求不明确。
  • 您可能还想查看您的代码在做什么。我在你的任何'ActiveDocument.Paragraphs(1).Range.Text = vbCrLf' 行中都看不到任何点,因为你跟随那些'wrdApp.ActiveDocument.Content.Delete',这也让我想知道你为什么'打开一个现有文档只是为了删除它的所有内容...

标签: excel vba ms-word


【解决方案1】:

很抱歉将其发布为答案:这是因为我没有足够的业力点数来发表评论。

如果您要一直使用类似的文档,那么我实际上会创建一个带有书签的模板。然后基于该模板创建一个文档。

这会为您提供正确格式的文档,然后您所要做的就是插入一些代码,例如:

wrdDoc.Bookmarks("bmkScrewData").Range.Text = Sheets("SCREW").Range("H1:J11")

假设您有一个名为 bmkScrewData 的书签。仅基于模板打开文档然后尝试将内容强制转换为空白文档要容易得多。这样您就可以完全控制您的环境。

这也意味着您可以避免在新的 Word 文档中删除所有默认 gubbins。

【讨论】:

  • 我使用的不是同一个word文件,它现在一直从互联网上提取。
  • 在这种情况下,您将不得不弄清楚如何识别相关位置(例如第 x 段,或始终位于相同相对位置的特定字符串)。
  • 查看代码,但是,我想知道文档是否是空白文档:这来自删除。那么,如果是这样的话,那为什么不将文档基于模板然后保存到远程位置呢?
  • @macropod 感谢您的评论。我如何识别特定的段落位置?
  • @Shoeless 基本上它是一个存储在 Intranet 中的 word 模板,我下载它并删除模板中已经存在的一些指南,并尝试使用宏将数据放入 excel 中,但它被粘贴在文档的顶部而不是我希望它被粘贴在特定的位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 1970-01-01
  • 1970-01-01
  • 2019-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多