How to setup a conversion from Excel Table to PowerPoint Presentation - excel

I would like to create a presentation based on data sorted in rows:
That, in the PowerPoint, would appear as this
But I am having difficulties understanding the correct syntax to properly have this done inside PowerPoint, rather than the Excel where the data comes from: how to declare/deal with the range of cells that become each a slide and in each of them of how to fill the relative placeholder, or "transposed/cut" place in table. I have looked everywhere, the very few pages/articles I found are not clear and overall short of explanation. I am stuck at the very beginning of this as I don't know how to set up the variable range of cells or if it should be an array to split later in different ranges, I would know how to continue, once I understood how to link Excel to PowerPoint Layouts/Slides/Objects.
I know I have to set a counter for each step, i.e. on for the change in Section #, in in the Slide # etc., mostly I find not clear how to translate the different parts of the table in rows and then section of rows.
EDIT: With code I have come up so far, this was the most helpful resource I could find. However I have the problem I was mentioning before: I do I swap the row I have left to columns in the table? How do I change them in a Range?
I referenced Excel for PowerPoint as from the original code, but the selection does no get recognized in POwerPoint (as said above, I would like to use it in PPT, not in Excel) . However, it works only in Excel, I have an error at For Each DataRow In DataRange.Rows variable not set when running as pptm. (reciprocal Libraries enabled in both programs).
From Excel, I can populate the title and the heading (so "AAA" and "aa") but I do not know how to progress in the cells, transposing the values for some columns and then restart.
Update:
I added a variable for the the columns of the source, but I am not sure how to deal with it. I'm so close but I don't know how to finish it. I introduced the variable FirstRowToColumn as range (columns E to the Excel screenshot below, that would become the first column of the tabel in PowerPoint), but I don't know how to declare this and the others range and paste them into the table. Could someone please teach me this or point to the solution, am I at least close ?
Edit2: added, with which I would copy the range and paste transposed, but it says the area is different.
Edit3: I can paste, I have to fix the counter to have the table in each slide, but the question of how to transpose remains and on top of that how to write the values in the Powerpoint table.
Edit 4:
I am trying a new way, by pasting in the Object placeholder id, but I saee nothing appearing in the table.
Sub General_Namer_For_Slides_And_Shapes()
Dim AnySlide As Slide
Dim AnyShape As Shape
Set AnySlide = Application.ActivePresentation.Slides(1)
For Each AnyShape In AnySlide.Shapes
Debug.Print "Application.ActivePresentation.Slides(1) AnySlide.Shapes AnyShape.Name " & AnyShape.Name & " AnyShape.Id "; AnyShape.Id '''names of each shape and their id '''removed " Slide " & AnySlide.SlideID&;
Next
Debug.Print "ActivePresentation.Slides(1).CustomLayout.Name " & ActivePresentation.Slides(1).CustomLayout.Name & " ActivePresentation.Slides(1).CustomLayout.Index " & ActivePresentation.Slides(1).CustomLayout.Index&;
Debug.Print " There are " & ActivePresentation.SlideMaster.Design.SlideMaster.CustomLayouts(4).Shapes.Count & " shapes in the Layout slide (SlideMaster View)"
'Debug.Print "ActivePresentation.Designs(4).Name = " & ActivePresentation.Designs(1).SlideMaster.CustomLayouts(4); ""
'Debug.Print " ActivePresentation.Designs.Name" & ActivePresentation.SlideMaster.Shapes.Placeholders. & ; ActivePresentation.Designs(4).Index; " & ActivePresentation.Designs(4).Index "
End Sub
Set NewTable = sld.Shapes.AddTable(12, 4)
FirstRowToColumn.Cells.PasteSpecial Paste:=-4163, Transpose:=True
to
Sub LoopRowsSelectedXCLToPPT()
Dim xlApp As Object
Dim xlWorkBook As Object
Dim xlSheet As Object
Dim DataRange As Range 'used
Dim DataRow As Range 'used
Dim DataCol As Range 'used
Dim PPTrng As Range ''cloning here the above to use in PowerPoint
Dim ShpRng As ShapeRange ''cloning here the data raw as range of shapes i could create later
Dim ShpCll As Shape
Dim AppPPT As PowerPoint.Application
Dim Pres As PowerPoint.Presentation
Dim sld As PowerPoint.Slide
Dim AppXCL As Excel.Application 'repeated the same as above with Excel as argument
Dim InputSheet As Excel.Worksheet
Set AppPPT = GetObject(, "PowerPoint.Application")
Set Pres = AppPPT.ActivePresentation
Set AppXCL = GetObject(, "Excel.Application")
Set InputSheet = AppXCL.ActiveSheet
Dim RowCounter As Integer
Dim ColCounter As Integer
Dim iRow As Integer
Dim iColumn As Integer
Dim FirstRowToColumn As Range
Dim SecondRowToColumn As Range
RowCounter = 0
ColCounter = 0
Set DataRange = Selection
For Each DataRow In DataRange.Rows
RowCounter = RowCounter + 1
Set sld = Pres.Slides.AddSlide(Pres.Slides.Count + 1, Pres.SlideMaster.CustomLayouts(4))
sld.Shapes.Title.TextFrame.TextRange.Text = DataRow.Cells(3, 3)
sld.Shapes.Placeholders(4).TextFrame.TextRange.Text = DataRow.Cells(3, 4)
' For Each DataCol In DataRange.Columns
ColCounter = ColCounter + 1
Set FirstRowToColumn = DataRange.Range(Cells(RowCounter + 1, 5), Cells(RowCounter + 1, 10))
FirstRowToColumn.Copy
Set NewTable = sld.Shapes.AddTable(12, 4)
sld.Shapes.Placeholders(4).TextFrame.TextRange.Text = FirstRowToColumn.Cells(1, 5)
' FirstRowToColumn.Cells(1, 10) =
' With sld.Shapes.Placeholders
' NewTable.Range(1,1)
'
'
' End With
' With sld.Shapes.Paste.SpecialPaste:=-4163, Transpose:=True
Next DataRow
Debug.Print RowCounter
Debug.Print ColCounter
End Sub

You may have to finesse the details but this works for me:
Sub LoopRowsSelectedXCLToPPT()
Const TABLE_COLS As Long = 5 '# of columns in PPT tables
Const BLOCK_SIZE As Long = 5
Dim Datarange As Range, rw As Range, rng As Range, i As Long, col As Long
Dim ppApp As PowerPoint.Application, pres As PowerPoint.Presentation
Dim sld As PowerPoint.Slide, newTable As PowerPoint.Table
On Error Resume Next
Set ppApp = GetObject(, "PowerPoint.Application")
Set pres = ppApp.ActivePresentation
On Error GoTo 0
If pres Is Nothing Then
MsgBox "Destination presentation must be open in PowerPoint", vbCritical
Exit Sub
End If
Set Datarange = Selection
For Each rw In Datarange.Rows
Set sld = pres.Slides.AddSlide(pres.Slides.Count + 1, _
pres.SlideMaster.CustomLayouts(2))
Set newTable = sld.Shapes.AddTable(BLOCK_SIZE, TABLE_COLS).Table
col = 0
Set rng = rw.Cells(5).Resize(1, BLOCK_SIZE) 'first BLOCK_SIZE cells starting from Col E
Do While Application.CountA(rng) > 0 'while have any data in `rng`
col = col + 1
If col > TABLE_COLS Then Exit Do 'ran out of columns in the PPT table...
For i = 1 To BLOCK_SIZE 'fill column # col
newTable.Cell(i, col).Shape.TextFrame2.TextRange.Text = rng.Cells(i).Value
Next i
Set rng = rng.Offset(0, BLOCK_SIZE) 'next block of cells to the right
Loop
Next rw
End Sub

Related

Excel VBA code to copy and paste table rows to PowerPoint until specific row height is met

I already have a working code that copies a table from Excel to PowerPoint and creates more slides and tables (splits the large table into multiple ones) if the sum of the row heights reaches a certain threshold in Excel:
Sub PowerPointTableSplit()
Dim rng As Range
Dim PowerPointApp As Object
Dim myPresentation As Object
Dim mySlide As Object
Dim myShape As Object
Dim lCol As Long
Dim lRow As Long
Dim LastRow As Long
Dim i As Long
Dim j As Integer
Dim rngH As Range
Dim wss As Worksheet
Set wb = Workbooks("Automation Tool.xlsm")
Set ws = wb.Sheets("630")
Set rngH = ws.Range("A1:AB1") 'Header Row (same for all tables)
LastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
With ws.Range("A1:AB" & LastRow)
.Font.Name = "Arial"
.Font.Size = 6
End With
ws.Range("A1:A" & LastRow).EntireRow.AutoFit
i = 2
Set wss = wb.Worksheets.Add
Set PowerPointApp = GetObject(class:="PowerPoint.Application")
Set myPresentation = PowerPointApp.ActivePresentation
'Loop through excel table and cut it after X rows to make it fit on PowerPoint, Copy & Paste table
'wss is a temporary excel sheet to store every X rows (will be deleted at the end)
Do While i <= LastRow
Z = 1 'counter to check row height in excel
RowHeight = 0
Do Until RowHeight > 600
RowHeight = RowHeight + ws.Rows(Z).Height
Z = Z + 1
Loop
j = Application.Min(i + Z, LastRow)
Union(rngH, ws.Range("A" & i, ws.Range("AB" & j))).Copy
wss.Range("A1").PasteSpecial Paste:=xlPasteColumnWidths
wss.Range("A1").PasteSpecial Paste:=xlPasteValues
wss.Range("A1").PasteSpecial Paste:=xlPasteAllUsingSourceTheme
sld.Shapes.PasteSpecial DataType:=ppPasteHTML, Link:=msoFalse
wss.Range("A1:AB" & j - i + 2).Copy
Set sld = myPresentation.Slides.Add(myPresentation.Slides.Count + 1, ppLayoutBlank)
i = j + 1
Loop
'Delte temporary excel sheet wss as not needed anymore
Application.DisplayAlerts = False
wss.Delete
Application.DisplayAlerts = True
Set wss = Nothing
End Sub
After this I am using a code to strech the table in PowerPoint to the whole available space on the slide, this also makes it tricky for me to get the real row height in PowerPoint using the code above as I would have to check the real height after streching the table.
Sub AutoFitTables()
Dim s As Slide
Dim oSh As Shape
Dim oTbl As Table
Dim lRow As Long
Dim lCol As Long
ScreenUpdating = False
For Each s In ActivePresentation.Slides
'ActivePresentation.Slides(Slide.SlideIndex(s)).Select
ActivePresentation.Slides(s.SlideIndex).Select
For Each oSh In s.Shapes
If oSh.HasTable Then
oSh.Left = 0 * 28.3
oSh.Top = 1.5 * 28.3
oSh.Width = 33.867 * 28.35
oSh.ZOrder msoSendToBack
Set oTbl = oSh.Table
For lRow = 1 To oTbl.Rows.Count
For lCol = 1 To oTbl.Columns.Count
With oTbl.Cell(lRow, lCol).Shape
.TextFrame.TextRange.Font.Name = "Arial"
.TextFrame.TextRange.Font.Size = 6
.TextFrame2.VerticalAnchor = msoAnchorMiddle
oTbl.Rows(lRow).Height = 0.5
End With
Next lCol
Next lRow
End If
Next oSh
Next s
ActivePresentation.Slides(1).Select
End Sub
However, since I still want to copy a much wider table, the format in the table shifts as soon as I copy it into PowerPoint, so that the table is too large to be seen completely, the code does not work.
I already have an idea, but the implementation fails. I want to copy the table row after row and after each copy check the total row height in PowerPoint and jump to the next page if the row height of 450 is reached. For this the following code comes into question:
sld.Shapes(X).Table.Rows(Y).Height 'with X and Y looping
I would be thankful for any help and hints.

Copying filtered cells to powerpoint table

Im relatively new to VBA. Im currently trying to run a code that copies filtered visible cells into powerpoint as a table. The dataset is rather huge and will continue to grow. How do I make the code dynamic and format the table that's being pasted into powerpoint?
Im getting an error Run time error '-2147188160 (80048240)': Shapes(unknown member) : Integer out of range. 2795 is not in the valid range of 1 to 75"
I would also like the data set to be formatted whereby the first and second column thats copied from the excel sheet gets transposed as the column headers in ppt.
The table looks like this in excel:
Product Code
Product Name
Keyword
Country
Status
Description
123456
Kobe Chicken
Chicken
Japan
Imported
NIL
643734
Hanwook Beef
Beef
Korea
Exported
NIL
The format i'd like in ppt:
123456 Kobe Chicken
643734 Hanwook Beef
(If the products list go on the products would be added via columns)
Country
Japan
Korea
NIL
Status
Imported
Exported
NIL
Description
NIL
NIL
Below is my code:
Also, is there anyway I can get the user to select from the dropdown menu of keyword to set the filtering criterea rather than entering it as a userinput for the code to filter out cells that match the criterea?
Sub Export_Range()
Dim userin As Variant
Dim userin2 As Variant
Dim pp As New PowerPoint.Application
Dim ppt As PowerPoint.Presentation
Dim sld As PowerPoint.Slide
Dim shpTable As PowerPoint.Shape
Dim i As Long, j As Long
Dim rng As Excel.Range
Dim sht As Excel.Worksheet
'To set range
userin = InputBox("Please enter the product you'd like to filter by: ")
userin2 = InputBox("Yes or No?: ")
set rng = Range("B$16:$AG$2810").Select
Selection.AutoFilter
ActiveSheet.Range("$B$16:$AG$2810").AutoFilter Field:=3, Criteria1:=userin
ActiveSheet.Range("$B$16:$AG$2810").AutoFilter Field:=4, Criteria1:=userin2
'This hides columns that are not needed in copying to ppt
Range("E16").EntireColumn.Hidden = True
Range("G16").EntireColumn.Hidden = True
Range("H16").EntireColumn.Hidden = True
Range("J16").EntireColumn.Hidden = True
Range("M16").EntireColumn.Hidden = True
Range("O16").EntireColumn.Hidden = True
Range("P16").EntireColumn.Hidden = True
Range("Q16").EntireColumn.Hidden = True
'Creates new ppt, and adds selected info into table
pp.Visible = True
If pp.Presentations.Count = 0 Then
Set ppt = pp.Presentations.Add
Else
Set ppt = pp.ActivePresentation
End If
Set sld = ppt.Slides.Add(1, ppLayoutTitleOnly)
Set shpTable = sld.Shapes.AddTable(rng.Rows.Count, rng.Columns.Count)
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
shpTable.Table.Cell(i, j).Shape.TextFrame.TextRange.Text = _
rng.Cells(i, j).Text
Next
Next
For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count
If (rng.Cells(i, j).MergeArea.Cells.Count > 1) And _
(rng.Cells(i, j).Text <> "") Then
shpTable.Table.Cell(i, j).Merge _
shpTable.Table.Cell(i + rng.Cells(i, j).MergeArea.Rows.Count - 1, _
j + rng.Cells(i, j).MergeArea.Columns.Count - 1)
End If
Next
Next
sld.Shapes.Title.TextFrame.TextRange.Text = _
rng.Worksheet.Name & " - " & rng.Address
End Sub
Here's an example of how to do this. I'm not sure if you simplfied your actual use case but I used this table for testing:
End Result:
Code:
Sub Tester()
'Add project reference to `Microsoft PowerPoint xx.x Object Library`
Dim loProds As ListObject, rngVis As Range, colKeyWord As ListColumn
Dim c As Range, rw As Range, visCount As Long, col As Long
Dim ppApp As PowerPoint.Application, ppPres As PowerPoint.Presentation
Dim ppSlide As PowerPoint.Slide, pptable As PowerPoint.Table
Dim indxProdCode As Long, indxProdName As Long
Dim indxCountry As Long, indxStatus As Long, indxDescr As Long
'info is in listobject "Products" on worksheet "Listing"
Set loProds = ThisWorkbook.Worksheets("Listing").ListObjects("Products")
'filter on Keyword = "Beef"
loProds.ShowAutoFilter = True
Set colKeyWord = loProds.ListColumns("Keyword")
loProds.Range.AutoFilter Field:=colKeyWord.Index, Criteria1:="Beef"
'get visible cells in keyword column
On Error Resume Next 'ignore error if no visible cells
Set rngVis = colKeyWord.DataBodyRange.SpecialCells(xlCellTypeVisible)
On Error GoTo 0 'stop ignoring errors
If rngVis Is Nothing Then 'no rows left after filtering?
MsgBox "No rows visible after applying filter...", vbExclamation
Exit Sub
End If
visCount = rngVis.Cells.Count 'how many visible rows left?
'start PPT, add a new presentation, and put a table on slide 1
Set ppApp = New PowerPoint.Application
ppApp.Visible = True
Set ppPres = ppApp.Presentations.Add()
Set ppSlide = ppPres.Slides.Add(1, ppLayoutTitleOnly)
Set pptable = ppSlide.Shapes.AddTable(4, visCount + 1).Table
SetText pptable.cell(2, 1), "Country" 'fixed row headers in column 1
SetText pptable.cell(3, 1), "Status"
SetText pptable.cell(4, 1), "Description"
'find the column indexes of the content we want to extract from `loProds`
indxProdCode = loProds.ListColumns("Product Code").Index
indxProdName = loProds.ListColumns("Product Name").Index
indxCountry = loProds.ListColumns("Country").Index
indxStatus = loProds.ListColumns("Status").Index
indxDescr = loProds.ListColumns("Description").Index
col = 1
'loop over each visible row and populate a new column in the table
For Each c In rngVis.Cells
Set rw = Application.Intersect(c.EntireRow, loProds.DataBodyRange) 'the table row for this cell
col = col + 1 'next ppt table column
SetText pptable.cell(1, col), rw.Cells(indxProdCode).Value & " " & rw.Cells(indxProdName).Value
SetText pptable.cell(2, col), rw.Cells(indxCountry).Value
SetText pptable.cell(3, col), rw.Cells(indxStatus).Value
SetText pptable.cell(4, col), rw.Cells(indxDescr).Value
Next c
End Sub
'helper method for setting table cell text
Sub SetText(cell As PowerPoint.cell, v)
cell.Shape.TextFrame.TextRange.Text = v
End Sub

Check if excel range has shape with VBA

Hi I'm trying to work through a table downloaded from a 3rd party that uses ticks (shapes) rather than text in the cells. The shapes have no textframe characters. I can't filter the ticks in excel so I want to replace then with text e.g. Yes. Here is my working code but get run time error 438 due to object errors I have tried the excel vba object model but can't get it to work. The VBE doesn't seem to have the Selection.ShapeRange
https://learn.microsoft.com/en-us/office/vba/api/excel.shape
https://learn.microsoft.com/en-us/office/vba/api/excel.shaperange
Here is my code
Sub ReplaceShapeswithYes()
' Inserts text where a shape exists
Dim ws As Worksheet
Dim NumRow As Integer
Dim iRow As Integer
Dim NumShapes As Long
Set ws = ActiveSheet
NumRow = ws.UsedRange.Rows.Count
For iRow = 2 To NumRow
Cells(iRow, 10).Select
'NumShapes = ActiveWindow.Selection.ShapeRange.Count ' tried both
NumShapes = Windows(1).Selection.ShapeRange.Count
If NumShapes > 0 Then
Cells(iRow, 10).Value = "Yes"
End If
Next iRow
End Sub
Many thanks
To get all shapes of a sheet, simply loop over the Shapes-collection of the sheet.
The text of a shape can be read with TextFrame.Characters.Text, but to be on the save side, you will need to check if a shape has really text (there are shapes that don't have any), see https://stackoverflow.com/a/16174772/7599798
To get the position withing a sheet, use the TopLeftCell-property.
The following code will copy the text of all shapes into the sheet and delete the shapes:
Sub shapeToText(Optional ws As Worksheet = Nothing)
If ws Is Nothing Then Set ws = ActiveSheet
Dim sh As Shape
For Each sh In ws.UsedRange.Shapes
If Not sh.TextFrame Is Nothing Then
If sh.TextFrame2.HasText Then
Dim s As String
s = sh.TextFrame.Characters.Text
sh.TopLeftCell = s
sh.Delete
End If
End If
Next
End Sub
This has done the trick
Sub ReplaceShapes()
'Replace all ticks with text
Dim NoShapes As Long
Dim iShape As Long
Dim ws As Worksheet
Dim r As Range
Dim Shp As Shape
Set ws = ActiveSheet
NoShapes = ws.Shapes.Count
For iShape = NoShapes To 1 Step -1:
Set Shp = ws.Shapes(iShape)
Set r = Shp.TopLeftCell
r.Value = "Yes"
Next iShape
End Sub

How to find duplicates and list them separately using VBA in Excel 2016

The answer "How to find duplicates and list them separately using VBA in Excel?" is exactly what I am looking for. I need help editing the language to fit my spreadsheet. Any help is greatly appreciated. I am not a programmer, just an enduser who admires the power of VBA. Thank you.
I've tried to edit the syntax but i cannot get it work in my spreadsheet.
Sub find_dups()
' Create and set variable for referencing workbook
Dim wb As Workbook
Set wb = ThisWorkbook
' Create and set variable for referencing worksheet
Dim ws As Worksheet
Set ws = wb.Worksheets("Sheet1")
' Find current last rows
' For this example, the data is in column A and the duplicates are in column C
Dim lngLastRowME As Long
lngLastRowME = ws.Range("A29-7834-9-0003").End(xlUp).Row
Dim lngLastRowDups As Long
lngLastRowDups = ws.Range("C29-7834-9-0003").End(xlUp).Row
' Create and set a variable for referencing data range
Dim rngME As Range
Set rngME = ws.Range("a4:a" & lngLastRowME)
Dim lngRowCount As Long
lngRowCount = 0
Dim clME As Variant
Dim lngCount As Long
Dim lngRowIndexME As Long
Dim lngRowIndexDups As Long
lngRowIndexDups = lngLastRowDups + 1
' Variable to store those values we've already checked
Dim strAlreadySearched As String
For Each clME In rngME.Cells
' Reset variables
lngCount = 0
' See if we've already searched this value
If InStr(1, strAlreadySearched, "|" & clME.Value & "|") = 0 Then
' We haven't, so proceed to compare to each row
For lngRowIndexME = 1 To lngLastRowME
' If we have a match, count it
If rngME.Cells(lngRowIndexME, 1).Value = clME.Value Then
lngCount = lngCount + 1
End If
Next lngRowIndexME
' If more than 1 instance
If lngCount > 1 Then
' Dup's were found, fill in values under duplicates
ws.Cells(lngRowIndexDups, 3).Value = clME.Value
ws.Cells(lngRowIndexDups, 4).Value = lngCount
' Drop down a row
lngRowIndexDups = lngRowIndexDups + 1
' Capture this value so we don't search it again
strAlreadySearched = strAlreadySearched & "|" & clME.Value & "|"
End If
End If
Next clME
End Sub
runtime error 400
Screen Shot and Workbook

Creating a named range based on EXACT string values in a cell

I have the following code that goes through values that I have in column C. When it finds the word "Search", the code creates a named range called "Search" for columns D to F.
Dim featuresRng As Range
Dim rng As Range
Dim sht As Worksheet
Dim counter As Long
Dim cell As Range
Set sht = ThisWorkbook.Worksheets("Features")
Set featuresRng = sht.Range(sht.Range("C1"), sht.Range("C" & sht.Rows.Count).End(xlUp)) 'dynamically set the range of features
counter = 0 'this counter will help us avoid Union(Nothing, some range), which would give an error
For Each cell In featuresRng 'loop through the range of features
If cell.Value = "Query Builder" Then
counter = counter + 1
If counter = 1 Then
Set rng = sht.Range(cell.Offset(0, 1), cell.Offset(0, 3))
Else
Set rng = Union(rng, sht.Range(cell.Offset(0, 1), cell.Offset(0, 3))) 'build the range
End If
End If
Next cell
Debug.Print rng.Address
ThisWorkbook.Names.Add "QuBuild", rng
However, whilst it appears fine on the Name Manager, when I use VBA to transition the range into a table in word, it seems to paste ALL values where the word "Search" is in column C.
Note, in column C I have a variety of cell values such as "Reporting", "Search", "Search and Filter", "Search and Analyse" etc. So, the range that is pasted into word appears to include the rows from the "Search and.." cells too.
This is the code I am using to export to a bookmarked position in word...
On Error Resume Next
Set WordApp = GetObject(class:="Word.Application")
'Clear the error between errors
Err.Clear
If WordApp Is Nothing Then Set WordApp = CreateObject(class:="Word.Application")
'Handle if the Word Application is not found
If Err.Number = 429 Then
MsgBox "Microsoft Word could not be found, aborting."
GoTo EndRoutine
End If
On Error GoTo 0
'Make MS Word Visible and Active
WordApp.Visible = True
WordApp.Activate
'Create a New Document
Set myDoc = WordApp.Documents.Open("Doc1")
'Copy Excel Table Range
'Copy and Paste Search into MS Word
If DoesNameRangeExist("Search") = True Then
Search.Copy
myDoc.Bookmarks("Search").Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
End If
Any help is, as always, much much appreciated!
The issues observed in the code
for opening New document in the word try something like `Set myDoc = Wordapp.Documents.Add'
Don't know what is DoesNameRangeExist, if is some sub routine the that is not produced in the code
The name of the NamedRange in question is "QuBuild" but you have used Name "Search"
Try following modification to make it work (as tested by me to work).
Add reference to Microsoft Word XX Object Library
in declaration section
Dim Nm As Name
Dim Wordapp As Word.Application
Dim myDoc As Word.Document
Finally in last section
Set myDoc = Wordapp.Documents.Add
For Each Nm In ThisWorkbook.Names
If Nm.Name = "QuBuild" Then
Nm.RefersToRange.Copy
Debug.Print Nm.RefersToRange.Address
myDoc.Bookmarks.Add "Search", myDoc.Range
myDoc.Range.PasteExcelTable False, False, False
Exit For
End If
Next Nm
Edit: However on trial it was observed that PasteExcelTable method is copying all the adjacent rows in between union ranges non-adjacent rows. May refer to the SO Post however answer in the post does not solve the problem and finally resorted to lengthy way below for correct operation. Invite & eager to learn more Simple Solutions to directly copy paste Union range from excel into Word from experts.
Code:
Set myDoc = Wordapp.Documents.Add
Dim RngtoCopy As Range
Dim xArea As Range, Rw As Range, col As Long, Tbl As Table
Dim TotalRow As Long
'If both the section of code are in the same procedure
'then it is not be necessary to use next loop to find NamedRange
'And can be directly refer as Rng.Areas instead of RngtoCopy.Areas
For Each Nm In ThisWorkbook.Names
If Nm.Name = "QuBuild" Then
Set RngtoCopy = Nm.RefersToRange
Exit For
End If
Next Nm
Set Tbl = myDoc.Tables.Add(myDoc.Range, 1, 3)
TotalRow = 0
For Each xArea In RngtoCopy.Areas
For Each Rw In xArea.Rows
TotalRow = TotalRow + 1
If TotalRow > Tbl.Rows.Count Then Tbl.Rows.Add
col = 0
For Each cell In Rw.Columns
col = col + 1
Tbl.cell(TotalRow, col).Range.Text = cell.Value
Next
Next
Next

Resources