简体   繁体   中英

How to copy text into word using excel VBA

How to paste a particular text into word at a particular location and header as well using VBA in excel. As of now, I can open the word using excel and I have got few things on to word using 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'

I'm able to copy the conten to word but not able to copy it to particular location.

Please help.

Sorry for posting this as an answer: this is because I don't have enough Karma Points to make this a comment.

If you are going to use a similar document all of the time then I would actually create a template with bookmarks in. Then create a document based on that template.

This then gives you a document of the right format and then all you have to do is to shove in some code such as:

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

Assuming that you have a bookmark called bmkScrewData. It's miles easier just to open a document based on a template then try to force stuff into a blank document. This way you can have your environment completely under your control.

It also means that you can avoid all the deletion of the default gubbins in the new Word document.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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