Advertisement
Guest User

Untitled

a guest
Jul 21st, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. Sub ActivateWordTransferData()
  2. Worksheets(“Sheet1”).Range(“A1:D4”).Copy
  3. ‘Declare Object variables for the Word application and file or document
  4. Dim wdapp As Object, wddoc As Object
  5. ‘Declare a String variable for the file name and folder path
  6. Dim strdocname As String
  7. ‘error handling is extremely important in making Excel work with Word
  8. On Error Resume Next
  9. ‘GetObject needs two parameters. The first is optional
  10. Set wdapp = GetObject(, “Word.Application”)
  11. If Err.Number = 429 Then
  12. Err.Clear
  13. ‘we create a new instance of MS Word
  14. Set wdapp = CreateObject(“Word.Application”)
  15. End If
  16. ‘Our application is made visible
  17. wdapp.Visible = True
  18. strdocname = “C:\our-inventory\inventory-report.docx”
  19. ‘we create a friendly message for the user
  20. If Dir(strdocname) = “” Then
  21. MsgBox “The file ” & strdocname & vbCrLf & “was not found ” & vbCrLf & “C:\our-inventory\.”, vbExclamation, “The document does not exist.”
  22. Exit Sub
  23. End If
  24. ‘we activate our MS Word instance
  25. wdapp.Activate
  26. Set wddoc = wdapp.Documents(strdocname)
  27. ‘we open MS Word file if it is not open
  28. If wddoc Is Nothing Then Set wddoc = wdapp.Documents.Open(strdocname)
  29. wddoc.Activate
  30. wddoc.Range.Paste
  31. wddoc.Save
  32. wdapp.Quit
  33. ‘Here we free memory allocated to our two object variables
  34. Set wddoc = Nothing
  35. Set wdapp = Nothing
  36. ‘The following line of code removes the selection of range A1:D4 in Excel
  37. Application.CutCopyMode = False
  38. End Sub
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement