The following code copies a single value into a bookmark in Word. I need it to copy a range of values like "A6:G20".
Sub test()
Dim objWord As Object
Dim ws As Worksheet
Set ws = Workbooks("Portfolio1").Sheets("Print")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "D:Q.docx" ' change as required
With objWord.ActiveDocument
.Bookmarks("monthtable").Range.Text = ws.Range("C6").Value ' here I need range of values to be selected instead of a single cell
End With
Set objWord = Nothing
End Sub
If suitable, you could copy and paste the range:
Range("A6:G20").Copy
.Bookmarks("monthtable").Range.PasteExcelTable False, False, False
There are a number of other Paste methods if you don't wish to paste as an Excel table. Use Word's VB Editor to discover these, or the Word Macro Recorder.
This is of course the important part:
With objWord.ActiveDocument
.Bookmarks("monthtable").Range.Text = ws.Range("C6").Value ' here i need range of values to be selected instead of a single cell
End With
Here you need to cycle through the ws.Range("..."), and for each cell in that range, concatenate that value onto the .Bookmarks.Range.Text value (Rather than setting it equal, which would overwrite). It's probably a good idea to first concatenate this into a string variable and then set the bookmark to that string variable's value, since that would avoid some potential interop issues.
Related
I have several sheets in one workbook. I want to copy-paste the data (entire content) from different sheets to sheet 1 (let's say from B6) based on the drop-down value in 'A2' in Sheet 1. Drop-down consists of names of all the other sheets. So, if I select Sheet 2 in drop-down, it should copy entire content from Sheet 2 to Sheet 1, starting from B6.
Here is the macro, I created for it. But it's not working. Can you help me figure out what's wrong with my code?
Sub Button21_Click()
Dim wb As Workbook
Dim criteria As String
Application.ScreenUpdating = False
'Set values for your variables.
Set wb = ThisWorkbook
criteria = wb.Sheets("Sheet1").Range("A2")
Dim TT As ListObject
For i = 1 To Sheets.Count
With Sheets(i)
For Each TT In Sheets(i).ListObjects
If TT.Name = criteria Then TT.Range.Copy Sheets("Sheet1").Range("B6:Q22").PasteSpecial: Exit Sub
Next
End With
Next
Application.ScreenUpdating = True
End Sub
Here's code that does work.
Sub Button21_Click()
Dim Wb As Workbook
Dim Criteria As String
Dim i As Integer ' loop counter: Sheets
Dim Tbl As ListObject ' loop object
'Set values for your variables.
Set Wb = ThisWorkbook
Criteria = Wb.Sheets("Sheet1").Range("A2")
Application.ScreenUpdating = False
For i = 1 To Wb.Sheets.Count ' { "Shees(1)" is in the ActiveWorkbook
' { which may be different from Wb
For Each Tbl In Wb.Sheets(i).ListObjects
If Tbl.Name = Criteria Then
Tbl.Range.Copy
Wb.Worksheets("Sheet1").Range("B6").PasteSpecial
Exit Sub
End If
Next Tbl
Next i
Application.ScreenUpdating = True
End Sub
You should declare all variables, not only objects. And it's better to prepare your tools before starting on the job, i.e. declare variables before writing code that uses them.
What's the point of declaring Set Wb = ThisWorkbook if you use the default workbook (= ActiveWorkbook) thereafter?
PasteSpecial needs its own line. The construct you used would deliver the argument for the Copy object's Destination property. The latter is an address and can't include the PasteSpecial method.
It's enough to specify the first cell to paste to.
Note that the ListObject's Range comprises of the entire table. Use the DataBodyRange to specify only data (without headers and totals).
Need to select several rows in word table from excel and then format
Copied table from excel to word
Can select a single row
Need to format selected row by adding space before in each cell
Need to do for several rows prefer to select range of cells and format all the same
Code:
Set objword = createobject(“word.application”)
Set objdoc = objword.documents.add
With objword
‘Lines of code for pagesetup working ok
‘Then paste excel table to word working ok
.selection paste
.visible = true
‘Have code sorted to select single row working ok
.activedocument.table(1).row(3).select
End with
Need to have code to select several rows
Then format by adding space before in each cell or entire row
Everything tried gives me unsupported function
Notes:
Will copy the Selected table in Excel to Word Document
Loop through all it's cell
You can change their Text , add space in front.
Skip rows in the loop using If condition.
Code:
Sub tb_copy()
Selection.Copy
Set objWord = CreateObject("word.application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
With objDoc
.Paragraphs(1).Range.PasteExcelTable False, False, False
For i = 1 To .tables(1).Rows.Count
For j = 1 To .tables(1).Columns.Count
Debug.Print .tables(1).cell(i, j).Range.Text
Next
Next
End With
End Sub
Problem:
.Selection.paste does not work
Need with statement with ObjDoc
I am trying to restrict the macro to a specific the Test! worksheet When I activate the macro pasted below and I am within the Test! worksheet, the macro works. However, when I try activating the macro on a different sheet, I receive an error. Any idea on what I need to do to modify the VBA code in order for it to be work any other worksheet within the workbook? Thanks
Sub Test ()
' Test Macro
'
' Keyboard Shortcut: Ctrl+Shift+B
'
Range ("Test!B1").Select
Selection.ClearContents
Range ("Test!B2").Select
Selection.ClearContents
Range ("Test!B3").Select
Selection.ClearContents
End Sub
You must reference the worksheet directly:
Dim ws as worksheet
set ws = Thisworkbook.Worksheets("Test")
with ws
.Range("B1:B3").ClearContents
end with
Other notes:
Don't use .Select or Selection. Simply operate on the objects directly.
You have String issues in your original code that would cause compile-time errors (fixed in my code)
You can clear the entire range in one line of code, rather than cell by cell
If the worksheet exists at compile-time in ThisWorkbook (i.e. the same file that's hosting the VBA code), then you don't need to retrieve the sheet at all - not by name, not by index.
VBA is already declaring a global Worksheet object variable for that sheet (and every sheet in ThisWorkbook). Verify the sheet's (Name) property; change it to TestSheet, then you can use TestSheet as an identifier anywhere in your code to refer to that sheet.
TestSheet.Range("B1:B3").ClearContents
And this code will work regardless of whether the user moved the sheet to another index/position in the workbook, or whether the user renamed the sheet's "tab" to something else.
ThisWorkbook.Worksheets(1).Range("B1:B3").ClearContents ' breaks if sheet is moved
ThisWorkbook.Worksheets("Test").Range("B1:B3").ClearContents ' breaks if sheet/tab is renamed
The Basics
If you want to learn something you should study versions 1 and 2, which are elaborate versions of versions 3 and 4 respectively.
Use Option Explicit to quickly find mistakes.
Use constants to be able to quickly change values.
Use object references to not have to type names on and on.
It is assumed that you will copy these codes in any module in the workbook where the worksheet 'Test' resides.
Option Explicit
Sub Test1()
Const cStrWs As String = "Test" 'Worksheet Name
Const cStrRng As String = "B1:B3" 'Range to 'DEL'
Dim oWs As Worksheet 'Worksheet Object
Dim oRng As Range 'Range Object
Set oWs = ThisWorkbook.Worksheets(cStrWs) 'Create a reference to the worksheet
Set oRng = oWs.Range(cStrRng) 'Create a reference to the range
oRng.ClearContents
End Sub
Sub Test2()
Const cStrWs As String = "Test" 'Worksheet Name
Const cStrCell As String = "B1" 'Cell to 'DEL'
Const cLngCells As Long = 3 'Number of cells
Dim oWs As Worksheet 'Worksheet Object
Dim oRng As Range 'Range Object
Set oWs = ThisWorkbook.Worksheets(cStrWs) 'Create a reference to the worksheet
Set oRng = oWs.Range(cStrCell) 'Create a reference to the cell range
oRng.Resize(3, 1).ClearContents
End Sub
Sub Test3()
ThisWorkbook.Worksheets("Test").Range("B1:B3").ClearContents
End Sub
Sub Test4()
ThisWorkbook.Worksheets("Test").Range("B1").Resize(3, 1).ClearContents
End Sub
The range of cells that I copy and paste into a word becomes a table. I want to know how to reference the word table and resize the row height and column width to fit a given size.
Sub RangeImporter()
Dim wrdApp As Word.Application
Dim rng As Range
Set wrdApp = New Word.Application
wrdApp.documents.Add
wrdApp.Visible = True
Set rng = Range("A27", Range("A27").End(xlDown))
rng.Copy
With wrdApp.Selection
.Paste
End With
wrdApp.Quit
Set wrdApp = Nothing
End Sub
I am very new to this and have very little background apart from what I have picked up here. Any help/tips/critiques would be much appreciated.
Thank you,
I found the answer here on the microsoft dev center site.
I changed:
With wrdApp.Selection
.Paste
End With
To
*
With wrdApp.Selection
.Paste
.Tables(1).Rows.SetHeight RowHeight:=InchesToPoints(0.2), HeightRule:=wdRowHeightExactly
End With
*
I'm sure I can apply this concept to columns, font size ect.
I want to know how to reference the word table and resize the row height and column width to fit a given size.
Sub Table4SlowRandy()
Dim aTbl As Word.Table
' paste a table from Excel
Selection.Range.Paste
' Assign pasted table to variable
Set aTbl = Selection.Range.Tables(1)
' Modify aTbl as you like
aTbl.Rows.SetHeight RowHeight:=InchesToPoints(0.2), HeightRule:=wdRowHeightExactly
' Deallocate aTbl
Set aTbl = Nothing
End Sub
I am trying to amend a VBA macro to enable pasting of an Excel range (as a picture, for formatting purposes) to a Word bookmark.
Sub test2()
Dim objWord As Object
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("PREMIUMS")
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\TEST\BTM Macro Template.docx"
With objWord.ActiveDocument
.Bookmarks("PLAN_1_SHEET").Range.Text = ws.Range("A34").Value
.Bookmarks("PLAN_2_SHEET").Range.Text = ws.Range("BTM_PREM").Value
End With
Set objWord = Nothing
End Sub
The macro pastes a single cell text reference fine ("A34"), but using the same code for a range "BTM_PREM") returns a type mismatch error.
I know it is due to the range not being a string, but can't seem to identify how to amend this line to enable pasting of "BTM_PREM", as a picture, at the "PLAN_2_SHEET" bookmark.
.Bookmarks("PLAN_2_SHEET").Range.Text = ws.Range("BTM_PREM").Value
This is a piece of code that works for me:
ActiveWorkbook.Sheets("Lease 1").Range("B16:AF25").CopyPicture Appearance:=xlScreen, Format:=xlPicture
wdoc.Bookmarks("Bkmrk1").Range.Paste
Application.CutCopyMode = False
It's not a complete macro, just a part of it so you'll have to adjust a bit, But I think you get the idea.
you could use Copy() method on Excel Range object and then either Paste() or PasteSpecial() or PasteExcelTable() Word Range object methods, like follows:
ws.Range("BTM_PREM").Copy
.Bookmarks("PLAN_2_SHEET").Range.Paste
or
ws.Range("BTM_PREM").Copy
.Bookmarks("PLAN_2_SHEET").Range.PasteSpecial Link:=True
or
ws.Range("BTM_PREM").Copy
.Bookmarks("PLAN_2_SHEET").Range.PasteExcelTable LinkedToExcel:=True, WordFormatting:=False, RTF:=True