Paste multiple sheets into a single Word document - vba

I'm trying to copy and paste each worksheet in a workbook onto a new sheet in a single Word document. Unfortunately it is only copying the contents of the first worksheet, though it does seem to be looping through all the worksheets. I thought that inserting a page break would work but it isn't. It also won't let me format it in Word. I want the contents of A1 to have a header style.
This is my code:
Sub ExceltoWord()
Dim ws As Worksheet
Dim Wkbk1 As Workbook
Set Wkbk1 = ActiveWorkbook
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each ws In Wkbk1.Worksheets
Wkbk1.ActiveSheet.Range("A1:A2").Copy
Dim wdapp As Object
Dim wddoc As Object
Dim Header As Range
'file name & folder path
Dim strdocname As String
On Error Resume Next
'error number 429
Set wdapp = GetObject(, "Word.Application")
If Err.Number = 429 Then
Err.Clear
'create new instance of word application
Set wdapp = CreateObject("Word.Application")
End If
wdapp.Visible = True
'define paths to file
strdocname = "P:\ImportedDescriptions.doc"
If Dir(strdocname) = "" Then
MsgBox "The file" & strdocname & vbCrLf & "was not found " & vbCrLf & "P:\ImportedDescriptions.doc", vbExclamation, "The document does not exist "
Exit Sub
End If
wdapp.Activate
Set wddoc = wdapp.Documents(strdocname)
If wddoc Is Nothing Then Set wddoc = wdapp.Documents.Open(strdocname)
Set Header = Range("A1")
'must activate to be able to paste
wddoc.Activate
wddoc.Range.Paste
Selection.WholeStory
Header.Style = ActiveDocument.Styles("Heading 2")
Selection.InsertBreak Type:=wdPageBreak
Next ws
wddoc.Save
'wdapp.Quit
Set wddoc = Nothing
Set wdapp = Nothing
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub

You are only copying from the active worksheet, which happens to be the first sheet in your case. Instead of:
For Each ws In ActiveWorkbook.Worksheets
ActiveWorkbook.ActiveSheet.Range("A1:A2").Copy
use:
For Each ws In ActiveWorkbook.Worksheets
ws.Range("A1:A2").Copy
This will copy each range in turn.

I think it is losing track of which workbook you started with when you activate Word. Save your workbook to a Workbook variable (i.e. Dim Wkbk1 As Workbook, Set Wkbk1 = ActiveWorkbook) then replace every instance of ActiveWorkbook in your code after that with Wkbk1 (in your For Each loop and every time you want to reference it inside the loop as well).

Related

Excel VBA: Save workbook as Word document

I would like to save my workbook (all sheets) as one Word document.
One sheets it's one page in document.
I find only code for save activeSheet.
Sub ExcelToWord()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim objWd As Object
Set objWd = CreateObject("word.application")
objWd.Visible = True
Dim objDoc As Object
Set objDoc = objWd.Documents.Add
objDoc.PageSetup.Orientation = 1 ' portrait = 0
Application.ScreenUpdating = False
ws.UsedRange.Copy
objDoc.Content.Paste
Application.CutCopyMode = False
Application.DisplayAlerts = False
objDoc.SaveAs (Application.ThisWorkbook.Path & "\dokument.docx")
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Thanks for your reply.
A couple quick things will get you to a solution.
The first is to loop through the worksheets in your workbook, like this:
Dim ws As Worksheet
For Each ws in ThisWorkbook.Sheets
Debug.Print "The used range is " & ws.UsedRange.Address
Next ws
The next part is to understand how adding content to a Word document is accomplished. The main concept involves where the insertion point for the document is located -- generally this is the current Selection.
When you cut and paste into a Word document, the content just pasted is still "selected". This means that any subsequent paste will effectively replace what you just inserted. So you have to move the selection point to the end of the document.
Putting it all together in an example program:
Option Explicit
Public Sub ExcelToWord()
Dim wb As Workbook
Set wb = ThisWorkbook
'--- create the Word document
Dim objWd As Word.Application
Set objWd = CreateObject("word.application")
objWd.Visible = True
Dim objDoc As Word.Document
Set objDoc = objWd.Documents.Add
objDoc.PageSetup.Orientation = 1 ' portrait = 0
Const wdPageBreak As Long = 7
Dim ws As Worksheet
For Each ws In wb.Sheets
ws.UsedRange.Copy
objWd.Selection.Paste
'--- advance the selection point to the end of
' the document and insert a page break, then
' advance the insertion point past the break
objDoc.Characters.Last.Select
objWd.Selection.InsertBreak wdPageBreak
objDoc.Characters.Last.Select
Next ws
'objDoc.SaveAs Application.ThisWorkbook.Path & ".\dokument.docx"
End Sub

Select range copy paste run macro clear loops till blank column,

I want to copy column A of karai1.xlsx to column A of wipbuj2.xlsx and then run the following macro to copy information to a Word document. Then I want to repeat this by copying column B of karai1.xlsx to column A of wipbuj2.xlsx and run the copy-to Word macro. Then column C of karai1.xlsx, etc, until I reach a blank column. Below is my attempt at copying the first column.
What i need is: copy column from workbook karai1.xlsx paste in workbook wipbuj2.xlsx in A(1st column) run macro/ code following
Dim wdApp As Object
Dim wd As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wd = wdApp.Documents.Add
wdApp.Visible = True
Sheets("Sheet5").Select
Range("A1:g39").Select
Selection.Copy
wdApp.Selection.PasteExcelTable False, False, True
wd.SaveAs
wd.Close
wdApp.Quit
then copy from column 2 from workbook karai1.xlsx paste in wippuj2.xlsx A column run macro run this loop till blank column in sheet karai1.xlsx .
Please help.
this is the code i was working
enter code here
Workbooks.Open Filename:="C:\Users\DO\Desktop\WIP buj 2.xlsx"
ActiveWindow.ScrollWorkbookTabs Sheets:=-1
Sheets("calculations").Select
Workbooks.Open Filename:= _
"C:\Users\do\Desktop\desktop\karai data\KARAI 1.xlsx"
Range("A1:A177").Select
Selection.Copy
Windows("WIP buj 2.xlsx").Activate
Sheets("calculations").Select
Range("A1").Select
ActiveSheet.Paste
Dim wdApp As Object
Dim wd As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wd = wdApp.Documents.Add
wdApp.Visible = True
Sheets("Sheet5").Select
Range("A1:g39").Select
Selection.Copy
wdApp.Selection.PasteExcelTable False, False, True
wd.SaveAs
wd.Close
wdApp.Quit
I believe by adding a simple loop across each column, stopping when the cell in row 1 is empty, you should be able to achieve what you are after.
Refactored code:
Sub test()
Dim wbSrc As Workbook
Dim wbDst As Workbook
Dim wsSrc As Worksheet
Dim wsDst As Worksheet
Dim wsCpy As Worksheet
Dim c As Long
Dim wdApp As Object
Dim wd As Object
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
wdApp.Visible = True
Set wbDst = Workbooks.Open(Filename:="C:\Users\DO\Desktop\WIP buj 2.xlsx")
Set wsDst = wbDst.Worksheets("calculations")
Set wsCpy = wbDst.Worksheets("Sheet5")
Set wbSrc = Workbooks.Open(Filename:="C:\Users\do\Desktop\desktop\karai data\KARAI 1.xlsx")
Set wsSrc = ActiveSheet ' Would be better to define this explicitly using the sheet name
c = 1
Do While Not IsEmpty(wsSrc.Cells(1, c).Value)
wsSrc.Cells(1, c).Resize(177, 1).Copy wsDst.Range("A1")
'Copy to Word
'Create new document
Set wd = wdApp.Documents.Add
'Copy Excel data
wsCpy.Range("A1:g39").Copy 'Avoid Excel's "Select" whenever possible!
'Paste in Word
wdApp.Selection.PasteExcelTable False, False, True
'Save and close
wd.SaveAs
wd.Close
'Next column
c = c + 1
Loop
wdApp.Quit
End Sub

Trying to copy data from several ranges in Excel to MS Word

I'm playing around with this code snippet, which I found on SO.
Sub Test()
Dim objWord As Object
Dim ws As Worksheet
Set ws1 = ThisWorkbook.Sheets("Contact Information1")
Set ws2 = ThisWorkbook.Sheets("Contact Information2")
'Set ws3 = ThisWorkbook.Sheets("Contact Information3")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\rshuell001\Desktop\Final Report.docx" ' change as required
With objWord.ActiveDocument
.Bookmarks("BkMark1").Range.Text = ws1.Range("A1:F24").Value
.Bookmarks("BkMark2").Range.Text = ws2.Range("A1:F8").Value
'.Bookmarks("Report3").Range.Text = ws3.Range("A1:F80").Value
End With
Set objWord = Nothing
End Sub
When I look at it, it makes sense. When I run the script, I get an error on this line:
.Bookmarks("BkMark1").Range.Text = ws1.Range("A1:F24").Value
The error message is:
Run-type error 13
Type mismatch
1) I'm not sure '.Bookmarks("BkMark1").Range.Text' will do what I want. I think it's more of a standard copy/paste.
2) I want to make sure the table fits in the Word document, so I'm going to need something like the line below, to get it to do what I want.
wd.Tables(1).AutoFitBehavior wdAutoFitWindow
Any ideas on how to make this work?
Thanks!
I came up with the script below. It does what I want.
Sub Export_Table_Word()
'Name of the existing Word doc.
'Const stWordReport As String = "Final Report.docx"
'Word objects.
Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Dim wdbmRange1 As Word.Range
'Excel objects.
Dim wbBook As Workbook
Dim wsSheet1 As Worksheet
Dim rnReport1 As Range
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set WDApp = New Word.Application
'Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\" & stWordReport)
Set WDDoc = WDApp.Documents.Open("C:\Users\rshuell001\Desktop\Final Report.docx")
'Delete old fields and prepare to replace with new
Dim doc As Document
Dim fld As Field
Set doc = WDDoc
For Each fld In doc.Fields
fld.Select
If fld.Type = 88 Then
fld.Delete
End If
Next
Set wsSheet = wbBook.Worksheets("Contact Information1")
Set rnReport = wsSheet.Range("BkMark1")
Set wdbmRange = WDDoc.Bookmarks("BkMark1").Range
'Turn off screen updating.
Application.ScreenUpdating = False
'Copy the report to the clipboard.
rnReport.Copy
'Select the range defined by the "Report" bookmark and paste in the report from clipboard.
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(1).AutoFitBehavior wdAutoFitWindow
Set wsSheet = wbBook.Worksheets("Contact Information2")
Set rnReport = wsSheet.Range("BkMark2")
Set wdbmRange = WDDoc.Bookmarks("BkMark2").Range
Application.ScreenUpdating = False
rnReport.Copy
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(2).AutoFitBehavior wdAutoFitWindow
Set wsSheet = wbBook.Worksheets("Contact Information3")
Set rnReport = wsSheet.Range("BkMark3")
Set wdbmRange = WDDoc.Bookmarks("BkMark3").Range
Application.ScreenUpdating = False
rnReport.Copy
With wdbmRange
.Select
.Paste
End With
WDDoc.Tables(3).AutoFitBehavior wdAutoFitWindow
'Save and close the Word doc.
With WDDoc
.Save
.Close
End With
'Quit Word.
WDApp.Quit
'Null out your variables.
Set fld = Nothing
Set doc = Nothing
Set wdbmRange = Nothing
Set WDDoc = Nothing
Set WDApp = Nothing
'Clear out the clipboard, and turn screen updating back on.
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
MsgBox "The report has successfully been " & vbNewLine & _
"transferred to " & stWordReport, vbInformation
End Sub

Search word doc for text and paste into excel file

I'm pretty sure I'm real close on this one, I used a combination of this question for text selection and this other question regarding importing tables for what I've gotten so far.
I'm trying to find certain value in a word file, with the most identifiable preceding text being a "VALUE DATE" on the line above it. The value I want is in the line below this "VALUE DATE". I want the macro to be able to search the word doc for the desired text and paste it into excel, as normally we would have to do this manually about 50 times. Very tedious.
For reference here's what the text looks like in the word doc.
TRANSACTIONS VALUE DATE
31-08-15 X,XXX.XX
I want to pull value X,XXX.XX and paste it into a destination in excel, let's just use A1 for simplicity.
Sub wordscraper9000()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
'''''dim tbl as object --> make string
Dim TextToFind As String, TheContent As String
Dim rng1 As Word.Range
FlName = Application.InputBox("Enter filepath of .doc with desired information")
'establish word app object
On Error Resume Next
Set oWordApp = GetObject(, "Word.application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
'open word doc
Set oWordDoc = oWordApp.documents.Open(FlName)
'--> enter something that will skip if file already open
'''''set tbl = oworddoc.tables(1) --> set word string
'declare excel objects
Dim wb As Workbook, ws As Worksheet
'Adding New Workbook
Set wb = Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs "C:\Users\iansch\Desktop\DummyWB.xlsx"
Set ws = wb.Sheets(1)
'what text to look for
TextToFind = "VALUE DATE"
'''''problems here below
Set rng1 = oWordApp.ActiveDocument.Content
rng.Find.Execute findtext:=TextToFind, Forward:=True
If rng1.Find.found Then
If rng1.Information(wdwithintable) Then
TheContent = rng.Cells(1).Next.Range.Text 'moves right on row
End If
Else
MsgBox "Text '" & TextToFind & "' was not found!"
End If
'copy text range and paste into cell A1
'tbl.range.copy
ws.Range("A1").Activate
ws.Paste
End Sub
At the line
set rng1.oWordApp.ActiveDocument.Content
I get a run-time 8002801d error - automation error, library not registered.
I couldn't find anything on here that was perfect for my case, however the 2nd question I linked to is very, very close to what I want, however I'm trying to import text rather than a table.
This will extract the "X,XXX.XX" value into a new Excel file, sheet 1, cell A1:
Option Explicit
Public Sub wordscraper9000()
Const FIND_TXT As String = "VALUE DATE"
Const OUTPUT As String = "\DummyWB.xlsx"
Dim fName As Variant, wrdApp As Object, wrdTxt As Variant, sz As Long, wb As Workbook
fName = Application.GetOpenFilename("Word Files (*.Doc*),*.Doc*", , _
"Enter filepath of .doc with desired information")
If fName <> False Then
'get Word text --------------------------------------------------------------------
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wrdApp = CreateObject("Word.Application")
Err.Clear
End If: wrdApp.Visible = False
wrdTxt = wrdApp.Documents.Open(fName).Content.Text: wrdApp.Quit
'get value ------------------------------------------------------------------------
sz = InStr(1, wrdTxt, FIND_TXT, 1)
If Len(sz) > 0 Then
wrdTxt = Trim(Right(wrdTxt, Len(wrdTxt) - sz - Len(FIND_TXT)))
wrdTxt = Split(Trim(Right(wrdTxt, InStr(wrdTxt, " "))))(0)
'save to Excel ----------------------------------------------------------------
Set wb = Workbooks.Add
wb.Sheets(1).Cells(1, 1) = wrdTxt
Application.DisplayAlerts = False
wb.Close True, CreateObject("WScript.Shell").SpecialFolders("Desktop") & OUTPUT
Application.DisplayAlerts = True
End If
End If
End Sub
.
This code is specific to this pattern:
"Reference" (any # of spaces) (any word without a space) (any # of spaces) "ExtractValue"
Search for reference (FIND_TXT)
Find and skip the next word (text without a space in it) after any number of spaces or empty lines
Extract the second word, separated by any number of spaces or lines from the skipped first word
Modifying your code a bit and if the information you want is in a fixed position within a Word table, you can do this:
Sub wordscraper90000()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
Dim TheContent As String
FlName = Application.GetOpenFilename("Word Files (*.Doc*),*.Doc*", , _
"Enter filepath of .doc with desired information")
'establish word app object
On Error Resume Next
Set oWordApp = GetObject(, "Word.application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
'open word doc
Set oWordDoc = oWordApp.Documents.Open(FlName)
'declare excel objects
Dim wb As Workbook, ws As Worksheet
'Adding New Workbook
Set wb = Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs "C:\Users\iansch\Desktop\DummyWB.xlsx"
Set ws = wb.Sheets(1)
TheContent = oWordDoc.Tables.Item(1).Cell(2, 3).Range.Text
ws.Range("A1").Activate
ws.Range("A1").Value = Trim(Replace(TheContent, Chr(7), Chr(32))) 'Remove strange character at the end
End Sub
Whereas the data to be extracted it is in row 2, column 3:

Baffling Run-time error 91

I'm new to VBA, have searched all over the place but can't seem to find a solution. I'm
getting a Run-time error 91: Object variable or With block variable not set error. Does anyone know why?
Much thanks.
Option Explicit
Sub Survey()
'Name of the existing Word doc.
Const stCoHydroSurveyTemplate As String = "Survey Template.docx"
'Define Word objects.
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim wdbmHeadLossTable As Word.Range
Dim wdbmRevenueTable As Word.Range
'Define Excel objects.
Dim wbBook As Workbook
Dim wsSheet As Worksheet
Dim rnHeadLossTable As Range
Dim rnRevenueTable As Range
'Initialize the Excel objects.
Set wbBook = ThisWorkbook
Set wsSheet = wbBook.Worksheets("Sheet1")
Set rnHeadLossTable = wsSheet.Range("HeadLossTable")
Set rnRevenueTable = wsSheet.Range("RevenueTable")
'Initialize the Word objets.
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "D:\Surveys" & stSurveyTemplate)
Set wdbmHeadLossTable = wdDoc.Bookmarks("HeadLossTable").Range
Set wdbmRevenueTable = wdDoc.Bookmarks("RevenueTable").Range
'If the macro has been run before, clean up any artifacts before trying to paste the table in again.
On Error Resume Next
With wdDoc.InlineShapes(1)
.Select
.Delete
End With
On Error GoTo 0
'Turn off screen updating.
Application.ScreenUpdating = False
'Copy the Head Loss Table to the clipboard.
rnHeadLossTable.Copy
rnRevenueTable.Copy
'Select the range defined by the "HeadLossTable" bookmark and paste in from the clipboard to the word doc "Survey Template".
With wdbmHeadLossTable
.Select
.PasteSpecial Link:=True, _
DataType:=wdPasteMetafilePicture, _
Placement:=wdInLine, _
DisplayAsIcon:=False
End With
With wdbmRevenueTable
.Select
.PasteSpecial Link:=True, _
DataType:=wdPasteMetafilePicture, _
Placement:=wdInLine, _
DisplayAsIcon:=False
End With
'Save and close the Word doc.
With wdDoc
.Save
.Close
End With
'Quit Word.
wdApp.Quit
'Null out your variables.
Set wdbmHeadLossTable = Nothing
Set wdbmRevenueTable = Nothing
Set wdDoc = Nothing
Set wdApp = Nothing
'Clear out the clipboard, and turn screen updating back on.
With Application
.CutCopyMode = False
.ScreenUpdating = True
End With
MsgBox "The Survey has successfully been " & vbNewLine & _
"transferred to " & stSurveyTemplate, vbInformation
End Sub
This line is incorrect:
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "D:\Surveys" & stSurveyTemplate)
Maybe you meant for it to be like this:
Set wdDoc = wdApp.Documents.Open("D:\Surveys" & stSurveyTemplate)
or this:
Set wdDoc = wdApp.Documents.Open(wbBook.Path & "\Surveys" & stSurveyTemplate)
What I noticed is that with the original code, it didn't throw an error and wdDoc was just set to Nothing. I removed the "sbBook.Path" and by mistake had an incorrect file name, and that did throw an error.