I manage to copy a range from excel to a newly opened WORD document and control the line spacing (thanks to some help Copy range from excel to word - set paragraph spacing to zero).
However, I do not manage to control the linespacing when I copy multiple ranges to multiple bookmarks in an opened and existing word file (document.docx). The code can be found below at the end of the post.
This code works for an excel file with multiple sheets. One sheet is a configuration sheet. It contains the name of the excel sheet containing the table (in range "Name") and links this to the bookmark name in word (in range BookmarkExcel")".
I suppose the problem is with this piece of the code:
Set wdTable = myDoc.Tables(myDoc.Tables.Count)
wdTable.Range.ParagraphFormat.SpaceAfter = 0
I tried all sorts of variations (e.g. replacing myDoc.Tables.Count by rep, 1, ...) but didn't manage to control the linespacing. What did I do wrong?
EDIT: I found the cause: the document contains already some tables (before and after the ones that I copy and paste) which causes the code for the line spacing not to work. Thus, how can I adapt my code such that it works for documents that already contain tables?
Sub ExcelTablesToWord()
Dim tbl As Range
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim WordTable As Word.Table
Sheets("Configuration").Select
n = ActiveSheet.UsedRange.Rows.Count
Set ListTables = Range("Name")
Set ListExcelBookmarks = Range("BookmarkExcel")
Set WordApp = GetObject(class:="Word.Application")
WordApp.Visible = True
Set myDoc = WordApp.Documents("document.docx")
For rep = 2 To n
SheetName = ListTables.Cells(rep, 1).Value
On Error Resume Next
Set existing = Sheets(SheetName)
existing.Select 'added this
lastColumn = ActiveSheet.UsedRange.Columns.Count
LastRow = ActiveSheet.UsedRange.Rows.Count
If ListExcelBookmarks.Cells(rep, 1).Value <> "" Then
Set tbl = Range(Cells(1, 1), Cells(LastRow, lastColumn))
tbl.Copy
myDoc.Bookmarks(ListExcelBookmarks.Cells(rep, 1).Value).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
Dim wdTable As Table
Set wdTable = myDoc.Tables(myDoc.Tables.Count)
wdTable.Range.ParagraphFormat.SpaceAfter = 0
End If
Next rep
End Sub
count the tables up to current bookmark and then add one to get the newly added table index
here's your code with what above and some other (hopefully) useful refactoring:
Option Explicit
Sub ExcelTablesToWord()
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim wdTable As Table
Dim rep As Long
Dim ListTables As Range
Dim ListExcelBookmarks As Range
Dim ws As Worksheet
Dim tabName As String
Set WordApp = GetObject(class:="Word.Application")
WordApp.Visible = True
Set myDoc = WordApp.Documents("document.docx")
With Worksheets("Configuration")
Set ListTables = .Range("Name")
Set ListExcelBookmarks = .Range("BookmarkExcel")
End With
For rep = 2 To ListExcelBookmarks.Rows.Count '<--| loop through bookmarks range, skipping first row
If ListExcelBookmarks.Cells(rep, 1).Value <> "" Then
tabName = ListTables.Cells(rep, 1).Value
If GetSheet(tabName, ws) Then '<-- GetSheet() returns 'True' if a worksheet named after 'tabName' is found and sets 'ws' to it. Otherwise it returns 'False'
ws.UsedRange.Copy
With myDoc
.Bookmarks(tabName).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
Set wdTable = .Tables(.Range(.Range.Start, .Bookmarks(tabName).Range.End).Tables.Count + 1) '<--| add one to the tables before current bookmark to get the newly added one right after it
wdTable.Range.ParagraphFormat.SpaceAfter = 0
End With
End If
End If
Next rep
End Sub
Function GetSheet(shtName As String, ws As Worksheet) As Boolean
On Error Resume Next
Set ws = Worksheets(shtName)
GetSheet = Not ws Is Nothing
End Function
Related
I am new in VBA, so I am not familiar with all its capabilities. I have a worksheet with many "tables" in it. By tables, I do not mean actual Excel Table Object but chunks of data that are separated into "tables" via color/border formatting.
I can find which cell a specific table starts by finding the cell which contains "RefNum:". However, to avoid false detection of table, I would like to double check the next cells after it.
Essentially, what I want is not just to find "RefNum:" but to find the position of 3x1 array which contains the ff in correct order:
- RefNum:
- Database:
- ToolID:
Only then can I be sure that what I found was a real table.
I am thinking of finding "RefNum:" and doing if-else for verification, but maybe there is a more sophisticated way of doing it?
Thanks for the help.
Try this code:
Sub FindTables()
Dim cell As Range
Dim firstAddress As String
With Range(Cells(1, 1), Cells(Rows.Count, Columns.Count))
Set cell = .Find("RefNum", LookIn:=xlValues)
firstAddress = cell.Address
Do
'check cell next to "RefNum" and one after that
If LCase(cell.Offset(0, 1).Value) = "database" And LCase(cell.Offset(0, 2).Value) = "toolid" Then
'here, cell is first cell (ref num) of the table
cell.Interior.ColorIndex = 4
End If
Set cell = .FindNext(cell)
Loop While Not cell Is Nothing And cell.Address <> firstAddress
End With
End Sub
Based from Michal's code, this is the answer I came up with. It works well except for one thing. It does not detect the 1st cell address, only the 2nd and succeeding. Can anyone see where I made an error?
Option Explicit
Public Sub LogSum()
'Declare variables
Dim shtMacro As Worksheet 'Sheet where macro button is located
Dim Fname As Variant 'List of user-selected files
Dim bookLOG As Workbook 'Active logsheet file
Dim shtLOG As Worksheet 'Active worksheet from current active workbook
Dim WS_Count As Integer 'Number of worksheets in active workbook
Dim CellDB As Range 'First cell output for find "RefNum"
Dim FirstAddress As String 'Address of the first CellDB
Dim i As Integer, j As Integer 'Loop iterators
'Prompt user to get logsheet filenames
Fname = Application.GetOpenFilename("ALL files (*.*), *.*,Excel Workbook (*.xlsx), *.xlsxm,Excel 97-2003 (*.xls), *.xls", , "Open Logsheet Files", , True)
If (VarType(Fname) = vbBoolean) Then Exit Sub
DoEvents
'Iterate per workbook
For i = LBound(Fname) To UBound(Fname)
Set bookLOG = Workbooks.Open(Filename:=Fname(i), UpdateLinks:=0, _
ReadOnly:=True, IgnoreReadOnlyRecommended:=True) 'Open workbook i
WS_Count = bookLOG.Worksheets.Count 'Store max number of sheets
Debug.Print bookLOG.Name 'Print the workbook filename in log
'Iterate per worksheet in workbook i
For j = 1 To WS_Count
Debug.Print bookLOG.Worksheets(j).Name 'Print the current sheet in log
Set CellDB = bookLOG.Worksheets(j).UsedRange.Find("RefNum:", LookIn:=xlValues) 'Search for "RefNum:"
If (Not (CellDB Is Nothing)) Then
bookLOG.Worksheets(j).UsedRange.Select
Debug.Print "Something's found here."
FirstAddress = CellDB.Address 'Assign the 1st search address
Debug.Print FirstAddress
Do 'Check cell next to "RefNum:" and one after that
If CellDB.Offset(1, 0).Value = "DATABASE: " And CellDB.Offset(2, 0).Value = "Tester:" Then
Debug.Print "Yay! Got You"
Debug.Print CellDB.Address
Else
Debug.Print "Oops. False Alarm"
End If
Set CellDB = bookLOG.Worksheets(j).UsedRange.FindNext(CellDB)
Loop While CellDB.Address <> FirstAddress
Else
Debug.Print "Nothing found here."
End If
Next j
Next i
End Sub
I am trying to copy and paste multiple tables from excel to word but it's giving me Subscript out of range error when I am trying to define tbl. I found the codes online and is trying to modify the codes to suit my needs.
Sub ExcelTablesToWord_Modified()
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim sheet As Excel.Worksheet
Dim tableName As String
With dict
.Add "TableA1", "TableA1"
.Add "TableA2", "TableA2"
.Add "TableB1", "TableB1"
.Add "TableB2", "TableB2"
.Add "TableC", "TableC"
.Add "TableD", "TableD"
.Add "TableE1", "TableE1"
.Add "TableE2", "TableE2"
.Add "TableF1", "TableF1"
.Add "TableF2", "TableF2"
'TODO: add the remaining WorksheetName/TableName combinations
End With
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
'Set Variable Equal To Destination Word Document
On Error GoTo WordDocNotFound
Set WordApp = GetObject(class:="Word.Application")
WordApp.Visible = True
Set myDoc = WordApp.Documents("a.docx")
On Error GoTo 0
'Loop Through Worksheets, and Copy/Paste Multiple Excel Tables
For Each sheet In ActiveWorkbook.Worksheets
tableName = dict(sheet.Name)
'Copy Table Range from Excel
sheet.ListObjects(tableName).Range.Copy
'Paste Table into MS Word (using inserted Bookmarks -> ctrl+shift+F5)
myDoc.Bookmarks(tableName).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
'Autofit the most-recently-pasted Table so it fits inside Word Document
myDoc.Tables(myDoc.Tables.Count).AutoFitBehavior (wdAutoFitWindow)
Next sheet
'Completion Message
MsgBox "Copy/Pasting Complete!", vbInformation
GoTo EndRoutine
'ERROR HANDLER
WordDocNotFound:
MsgBox "Microsoft Word file 'b' is not currently open, aborting.", 16
'Put Stuff Back The Way It Was Found
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
Below will copy the first Table in every worksheet and paste into Word doc, regardless of the Table Name. The bookmark names in the Word doc assumed to be simply start at 1 with prefix "bookmark".
If specific Table names are really required, then create a Collection for the names, and loop through each Table in each Worksheet, if that table name is in the Collection then proceed to copy.
Option Base 1 'Force arrays to start at 1 instead of 0
Sub ExcelTablesToWord()
Dim oWS As Worksheet
Dim tbl As Excel.Range
Dim WordApp As Object ' Word.Application
Dim myDoc As Object ' Word.Document
Dim x As Long ' Integer
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
'Set Variable Equal To Destination Word Document
On Error Resume Next
Set WordApp = GetObject(, "Word.Application")
If WordApp Is Nothing Then Set WordApp = CreateObject("Word.Application")
If WordApp Is Nothing Then GoTo WordDocNotFound
WordApp.Visible = True
Set myDoc = WordApp.Documents("a.docx")
If myDoc Is Nothing Then Set myDoc = WordApp.Documents.Open("a.docx")
If myDoc Is Nothing Then GoTo WordDocNotFound
'Loop Through and Copy/Paste Multiple Excel Tables
x = 1 ' For x = LBound(TableArray) To UBound(TableArray)
For Each oWS In ThisWorkbook.Worksheets
'Copy Table Range from Excel
'Set tbl = ThisWorkbook.Worksheets(x).ListObjects(TableArray(x)).Range
Set tbl = oWS.ListObjects(1).Range
If Not tbl Is Nothing Then
tbl.Copy
'Paste Table into MS Word (using inserted Bookmarks -> ctrl+shift+F5)
myDoc.Bookmarks("bookmark" & x).Range.PasteExcelTable LinkedToExcel:=False, WordFormatting:=False, RTF:=False
'Autofit Table so it fits inside Word Document
myDoc.Tables(x).AutoFitBehavior 2 ' (wdAutoFitWindow)
x = x + 1
End If
Next
On Error GoTo 0
'Completion Message
MsgBox "Copy/Pasting Complete!", vbInformation
GoTo EndRoutine
'ERROR HANDLER
WordDocNotFound:
MsgBox "Microsoft Word file 'b' is not currently open, aborting.", 16
'Put Stuff Back The Way It Was Found
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
The code I had originally provided was based on your original model, in which the corresponding Worksheet, Table, and Bookmark in each set had a different name.
Now that you have ensured that the names of the objects in each set are identical (which is a better model), try the following procedure. The only difference is that the Scripting.Dictionary has been eliminated, and the Worksheet name is being used to provide both the name of the Table and the name of the Bookmark (since all three values match now).
As before, this one has also been tested in Excel/Word 2016, and is functioning as expected:
Public Sub ExcelTablesToWord_Modified2()
Dim WordApp As Word.Application
Dim myDoc As Word.Document
Dim sheet As Excel.Worksheet
'Optimize Code
Application.ScreenUpdating = False
Application.EnableEvents = False
'Set Variable Equal To Destination Word Document
On Error GoTo WordDocNotFound
Set WordApp = GetObject(class:="Word.Application")
WordApp.Visible = True
Set myDoc = WordApp.Documents("a.docx")
On Error GoTo 0
'Loop Through Worksheets, and Copy/Paste Multiple Excel Tables
For Each sheet In ActiveWorkbook.Worksheets
'Copy Table Range from Excel
sheet.ListObjects(sheet.Name).Range.Copy
'Paste Table into MS Word (using inserted Bookmarks -> ctrl+shift+F5)
myDoc.Bookmarks(sheet.Name).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
'Autofit the most-recently-pasted Table so it fits inside Word Document
myDoc.Tables(myDoc.Tables.Count).AutoFitBehavior (wdAutoFitWindow)
Next sheet
'Completion Message
MsgBox "Copy/Pasting Complete!", vbInformation
GoTo EndRoutine
'ERROR HANDLER
WordDocNotFound:
MsgBox "Microsoft Word file 'b' is not currently open, aborting.", 16
'Put Stuff Back The Way It Was Found
EndRoutine:
'Optimize Code
Application.ScreenUpdating = True
Application.EnableEvents = True
'Clear The Clipboard
Application.CutCopyMode = False
End Sub
If you still receive the same error, then perhaps the Workbook is corrupted. In that case, try doing the following:
Create a new Workbook with one Worksheet
Rename the Worksheet so that its name matches the name of one of the Bookmarks in the Word document
Manually add a single, small, "testing-only" Table to the Worksheet (do not copy/paste one from the original Workbook)
Ensure that the Table's name is the same as the Worksheet's name
Copy/paste the above procedure into a new Module in that Workbook
Save the new Workbook
Ensure your Word document is open, and run the procedure
If that works, then you might consider recreating your entire original Workbook in the new Workbook. When doing so, if your datasets are large enough that you must copy/paste from the Original Workbook, use "Paste Special" with "Values Only" instead of just a normal Paste. Then, re-create any missing formatting manually. That way, it will be less likely that any corruption in the original Workbook will be transferred to the new one.
I keep having this issue of VBA either not having an object for the new sheet I want to merge, or having the subscript out of range issue come up. None of the things I tried ended up working.
Private Sub MergeButton_Click()
Dim filename As Variant
Dim wb As Workbook
Dim s As Sheet1
Dim thisSheet As Sheet1
Dim lastUsedRow As Range
Dim j As Integer
On Error GoTo ErrMsg
Application.ScreenUpdating = False
Set thisSheet = ThisWorkbook.ActiveSheet
MsgBox "Reached method"
'j is for the sheet number which needs to be created in 2,3,5,12,16
For Each Sheet In ActiveWorkbook.Sheets
For i = 0 To FilesListBox.ListCount - 1
filename = FilesListBox.List(i, 0)
'Open the spreadsheet in ReadOnly mode
Set wb = Application.Workbooks.Open(filename, ReadOnly:=True)
'Copy the used range (i.e. cells with data) from the opened spreadsheet
If FirstRowHeadersCheckBox.Value And i > 0 Then 'Only include headers from the first spreadsheet
Dim mr As Integer
mr = wb.ActiveSheet.UsedRange.Rows.Count
wb.ActiveSheet.UsedRange.Offset(3, 0).Resize(mr - 3).Copy
Else
wb.ActiveSheet.UsedRange.Copy
End If
'thisSheet = ThisWorkbook.Worksheets(SheetCurr)
'Paste after the last used cell in the master spreadsheet
If Application.Version < "12.0" Then 'Excel 2007 introduced more rows
Set lastUsedRow = thisSheet.Range("A65536").End(xlUp)
Else
Set lastUsedRow = thisSheet.Range("A1048576").End(xlUp)
End If
'Only offset by 1 if there are current rows with data in them
If thisSheet.UsedRange.Rows.Count > 1 Or Application.CountA(thisSheet.Rows(1)) Then
Set lastUsedRow = lastUsedRow.Offset(1, 0)
End If
lastUsedRow.PasteSpecial
Application.CutCopyMode = False
Next i
This is where I try to add an extra loop that copies the next sheet (which is Sheet12) but it comes up with the Subscript our of range error.
Sheets("Sheet3").Activate
Sheet.Copy After:=ThisWorkbook.Sheets
Next Sheet
It will then move to the next sheet to perform the loop again.
ThisWorkbook.Save
Set wb = Nothing
#If Mac Then
'Do nothing. Closing workbooks fails on Mac for some reason
#Else
'Close the workbooks except this one
Dim file As String
For i = 0 To FilesListBox.ListCount - 1
file = FilesListBox.List(i, 0)
file = Right(file, Len(file) - InStrRev(file, Application.PathSeparator, , 1))
Workbooks(file).Close SaveChanges:=False
Next i
#End If
Application.ScreenUpdating = True
Unload Me
ErrMsg:
If Err.Number <> 0 Then
MsgBox "There was an error. Please try again. [" & Err.Description & "]"
End If
End Sub
Any help an this would be great
Your source code is very confusing and I believe you're stumbling because the ActiveWorkbook and ActiveSheet change each time you open a new workbook. It's also not clear why you're copying/merging the data from each worksheet in every opened workbook and then copying Sheet3. You will help yourself by more clearly defining what and where your data is and how you're moving it around.
As an example (that may not solve your problem, because your problem is not clear), look at the code below to see how you can keep the sources and destinations straight within your loops. Modify this example as much as you need in order to match your exact situation.
Sub Merge()
'--- assumes that each sheet in your destination workbook matches a sheet
' in each of the source workbooks, then copies the data from each source
' sheet and merges/appends that source data to the bottom of each
' destination sheet
Dim destWB As Workbook
Dim srcWB As Workbook
Dim destSH As Worksheet
Dim srcSH As Worksheet
Dim srcRange As Range
Dim i As Long
Application.ScreenUpdating = False
Set destWB = ThisWorkbook
For i = 0 To FileListBox.ListCount - 1
Set srcWB = Workbooks.Open(CStr(FileListBox(i, 0)), ReadOnly:=True)
For Each destSH In destWB.Sheets
Set srcSH = srcWB.Sheets(destSH.Name) 'target the same named worksheet
lastdestrow = destSH.Range("A").End(xlUp)
srcSH.UsedRange.Copy destSH.Range(Cells(lastdestrow, 1))
Next destSH
srcWB.Close
Next i
Application.ScreenUpdating = True
End Sub
I need to activate a specific worksheet. The code is meant to create worksheets with a specif name. I need to paste something from a another worksheet into all these newly created worksheets. The code that I'm using is below. But I'm having a hard time activating the newly created worksheet to paste what I want.
Sub octo()
'Dim ws As Worksheet
Dim Ki As Range
Dim ListSh As Range
Workbooks.Open ("C:\Users\Dash\Dropbox\Randika\Misc\Emmash timesheets\timesheet.xlsx")
With Worksheets("PPE 05-17-15")
Set ListSh = .Range("B4:B" & .Cells(.Rows.Count, "B").End(xlUp).Row)
End With
On Error Resume Next
For Each Ki In ListSh
If Len(Trim(Ki.Value)) > 0 Then
If Len(Worksheets(Ki.Value).Name) = 0 Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = Ki.Value
'open template
Workbooks.Open ("C:\Users\Dash\Dropbox\Randika\Misc\Emmash timesheets\octo_template.xls")
Range("A1:L31").Select
Selection.Copy
Worksheets(Ki.Value).Activate
If ThisWorkbook.Saved = False Then
ThisWorkbook.Save
End If
End If
End If
Next Ki
End Sub
Both Workbooks.Open and Worksheets.Add return references to the opened and added objects, which you can use to directly access and modify them - and in your case, to paste data.
Example:
Dim oSourceSheet As Worksheet
Dim oTargetSheet As Worksheet
Set oSourceSheet = Sheet1 'Set reference to any sheet, Sheet1 in my example
Set oTargetSheet = Worksheets.Add(After:=Worksheets(Worksheets.Count))
oSourceSheet.Range("A1:L31").Copy
oTargetSheet.Paste
Set oSourceSheet = Nothing
Set oTargetSheet = Nothing
I think that is what you need. As what been mentioned by chris, there is no need Activate or Select. Hope the following code solve your problem.
Option Explicit
Dim MyTemplateWorkbook As Workbook
Dim MyDataWorkbook As Workbook
Dim MyTemplateWorksheet As Worksheet
Dim MyDataWorksheet As Worksheet
Dim MyNewDataWorksheet As Worksheet
Dim CurrentRange As Range
Dim ListRange As Range
Sub AddWSAndGetData()
Set MyTemplateWorkbook = Workbooks.Open("C:\Users\lengkgan\Desktop\Testing\MyTemplate.xlsx")
Set MyTemplateWorksheet = MyTemplateWorkbook.Sheets("Template")
Set MyDataWorkbook = Workbooks.Open("C:\Users\lengkgan\Desktop\Testing\MyData1.xlsx")
Set MyDataWorksheet = MyDataWorkbook.Sheets("PPE 05-17-15")
Set ListRange = MyDataWorksheet.Range("B4:B" & MyDataWorksheet.Cells(Rows.Count, "B").End(xlUp).Row)
Application.ScreenUpdating = False
On Error Resume Next
For Each CurrentRange In ListRange
If Len(Trim(CurrentRange.Value)) > 0 Then
If Len(MyDataWorksheet(CurrentRange.Value).Name) = 0 Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = CurrentRange.Value
Set MyNewDataWorksheet = MyDataWorkbook.Sheets(ActiveSheet.Name)
MyNewDataWorksheet.Range("A1:L31").Value = MyTemplateWorksheet.Range("A1:L31").Value
If MyDataWorkbook.Saved = False Then
MyDataWorkbook.Save
End If
End If
End If
Next CurrentRange
MyTemplateWorkbook.Close (False) 'Close the template without saving
End Sub
I want to copy the print area for landscape in Excel to my Word document, where I run the code from.
I am using
wb.Sheets("Sheet1").Range("A1:N33").Copy
to copy the area, but as the column width changes, it's useless.
Update:
I am using this to calculate my usable dimensions in my Word Document
With ActiveDocument.PageSetup
UsableWidth = .PageWidth - .LeftMargin - .RightMargin
UsableHeight = .PageHeight - .TopMargin - .BottomMargin
End With
I tried to scale my image to fit with:
Selection.PasteSpecial Link:=False, DataType:=wdPasteMetafilePicture, Placement:=wdInLine, DisplayAsIcon:=False
Selection.ShapeRange.Height = UsableHeight
Selection.ShapeRange.Width = UsableHeight
It does not quite do it. The best approach would be to set the image range before it copies.
Update2:
Dim objExcel As New Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Set wb = objExcel.Workbooks.Open("C:\test.xlsx")
Set ws = wb.Sheets("Sheet1")
This gives an error:
Set rngTemp = ws.Range("A1")
You can retrieve the print area information using this code:
Sub GetPrintArea()
Dim rngPrintArea As Range
'Put print area into range variable
Set rngPrintArea = Sheet1.Range(Sheet1.PageSetup.PrintArea)
'Perform operations on range - shows up in Immediate window:
Debug.Print rngPrintArea.Height
Debug.Print rngPrintArea.Width
Debug.Print rngPrintArea.Cells(rngPrintArea.Rows.Count, rngPrintArea.Columns.Count).Address
End Sub
This does not work if a print area is not already set - can you confirm if the Excel sheets are already set to landscape with a print area defined? If not, you'll need to find the paper dimensions and loop through cells until you find those which share the same Left and Top values (I think). You can set the PrintArea like this:
'Set print area
Sheet1.PageSetup.PrintArea = "$A1:$N33"
EDIT - This should do what you need now we know that the source dimensions are predefined - you'll need to set UseableWidth and UseableHeight in Word and either bring them into this sub using ByVal or a public variable:
Sub FindRange()
Dim rngTemp As Range, rngCopy As Range, rngTest As Range
Dim iCol As Integer, iRow As Integer
Set rngTemp = Sheet1.Range("A1")
'Get closest column
Do Until rngTemp.Left >= UseableWidth
Set rngTemp = rngTemp.Offset(0, 1)
Loop
iCol = rngTemp.Column
'Get closest row
Do Until rngTemp.Top >= UseableHeight
Set rngTemp = rngTemp.Offset(1, 0)
Loop
iRow = rngTemp.Row
Set rngCopy = Sheet1.Range("A1", Sheet1.Cells(iRow, iCol))
'Copy rngCopy into Word as you were before
End Sub