Remove part of the border of a table excel VBA - excel

There is a set of forms that we sometimes have to fill out at work, and I'm trying to automate the task by having excel VBA recreate the form as a word document and populate with the appropriate data and print as a pdf. I'm getting stuck on removing the border line style. I want there to be no border line on the left side. I have tried different approaches, and the one that seems the most likely that it should work based on my understanding is below:
(note: ".Border(xlEdgeleft).LineStyle = xlLineStyleNone" is the line that is giving me trouble)
Sub main()
Dim objWord As Object
Dim objDoc As Object
Dim objHdrRange As Object
Dim myTable As Object
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
Set objHdrRange = objDoc.Sections(1).headers(1).Range
Set myTable = objWord.activedocument.tables.Add(objHdrRange, 5, 5)
With myTable
.Borders.enable = True
.Border(xlEdgeleft).LineStyle = xlLineStyleNone
‘more code goes here later
End With
Set objDoc = Nothing
Set objHdrRange = Nothing
objWord.Quit
End Sub

xlEdgeLeft and xlLineStyleNone are from the Excel Object Model, not from the Word Object Model, and you need the latter.
Since you are late-binding, you could add the following lines:
Const wdBorderLeft As Long = -2
Const wdLineStyleNone As Long = 0
and replace xlEdgeLeft and xlLineStyleNone with these, respectively.
See the WdBorderType and WdLineStyle enum docs for more detail.

Related

Shapes.AddTextbox being placed at wrong position in Word doc after the first page

I am having this weird issue when I am trying to add textboxes in a Word document from an Excel file. Textboxes are being placed in a loop in all the pages which all contain a table. When I run the code, the first textbox is placed correctly but when I increment to go to next page (where there is a table), the textbox is placed at incorrect position.
I noticed that when I remove the table element the code works fine and all textboxes are placed correctly but when I add back the table, the first page comes out fine but the subsequent pages textboxes are placed incorrectly. Below is an example:
Here is a snippet of my code:
Public Sub test9()
Dim objWord As Object
Dim objDoc As Object
Dim box As Object
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open("C:\Users\user\Downloads\Test2.docx")
objWord.Visible = True
For i = 1 To 10
objWord.Selection.GoTo What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=i
Set doc = objWord.ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 53, 130, 20)
doc.TextFrame.TextRange.InsertAfter "Test Box" & i
Next i
End Sub
To reproduce the error you can create a tables in multiple pages and if you run, you'll see the output as shown in the picture.
I am not sure what is causing this or if I am missing anything, please point it out.
This worked for me - get the range of the page you want - then anchor the textbox shape to it.
I tested it in Word - you'll have to modify to match your object declarations
Sub test()
Dim i As Integer
Dim objTextBox As Object ' TextBox Shape
Dim objRge As Object ' Word Object Range
For i = 1 To ActiveDocument.ComputeStatistics(wdStatisticPages)
Set objRge = ActiveDocument.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=i)
Set objRge = objRge.GoTo(What:=wdGoToBookmark, Name:="\page")
' next you specify the page range as your textbox anchor parameter
Set objTextBox = ActiveDocument.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 53, 130, 20, Anchor:=objRge)
objTextBox.TextFrame.TextRange.InsertAfter "Test Box" & i
Next i
End Sub
If you're running from inside Excel and don't have a reference to Word, you'll need to predefine the Word constants - try this
Option Explicit
Const TestDoc As String = "C:\Users\<yourusername>\Documents\Test2.docx"
Public Sub TestFromExcel()
Dim objWord As Object
Dim objDoc As Object
Dim box As Object
' Define Word constants in Excel if you don't have a reference to WORD
Const wdGoToAbsolute As Long = 1
Const wdStatisticPages As Long = 2
Const wdGoToPage As Long = 1
Const wdGoToBookmark As Long = -1
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Open(TestDoc)
objWord.Visible = True
Dim i As Integer
Dim objTextBox As Object ' TextBox Shape
Dim objRge As Object ' Word Object Range
For i = 1 To objDoc.ComputeStatistics(wdStatisticPages)
Set objRge = objDoc.GoTo(What:=wdGoToPage, Which:=wdGoToAbsolute, Name:=i)
Set objRge = objRge.GoTo(What:=wdGoToBookmark, Name:="\page")
Set box = objDoc.Shapes.AddTextbox(msoTextOrientationHorizontal, 10, 53, 130, 20, Anchor:=objRge)
box.TextFrame.TextRange.InsertAfter "Test Box" & i
Next i
End Sub

Use Word Content Control Values for chart object in same Word doc

Using MS Word (in my case 2010 version), I have constructed a form with Content Control elements to be filled out by the user. Now I want certain entries (that I already gave titles to) be shown in a chart inside the same Word document (not in a separate Excel document).
This should be an automated process, so that if the user changes one of the Content Control entries, the chart updates itself automatically; I would also be OK if the user had to press a button in order to update the chart (but the user shouldn't have to click around a lot, since I must assume the user to have little skills.)
So I inserted an Excel chart object in my Word form document. I also wrote some VBA code inside this Excel object to read the Content Control values from the Word document as source for the chart. But I think what I really need is the VBA code to be in my Word document itself (for example to be executed upon click on a button by the user), yet I don't know how to address the Excel chart object and the cells within.
My VBA code inside the Excel object is:
Sub ChartDataAcquirer()
Dim wdApp As Object
Dim wdDoc As Object
Dim DocName As String
Dim ccX As String
Dim ccY As String
Dim datapairs As Integer
'''''''''' Variables '''''''''
DocName = "wordform.docm"
ccX = "titleX"
ccY = "titleY"
datapairs = 5
''''''''''''''''''''''''''''''
Set wdApp = GetObject(, "Word.Application")
Set wdDoc = wdApp.Documents(DocName)
Dim i As Integer
For i = 1 To datapairs
With ActiveSheet.Cells(i + 1, 1) ' The first row contains headline, therefore i+1
.Value = wdDoc.SelectContentControlsByTitle(ccX & i).Item(1).Range.Text ' The CC objects containing the x values have titles "titleX1", "titleX2" ..., therefore "ccX & i"
On Error Resume Next
.Value = CSng(wdDoc.SelectContentControlsByTitle(ccX & i).Item(1).Range.Text) ' To transform text into numbers, if user filled the CC object with numbers (which he should do)
End With
With ActiveSheet.Cells(i + 1, 2)
.Value = wdDoc.SelectContentControlsByTitle(ccY & i).Item(1).Range.Text
On Error Resume Next
.Value = CSng(wdDoc.SelectContentControlsByTitle(ccY & i).Item(1).Range.Text)
End With
Next
End Sub
I guess I need a similar code that is placed in and operates from the Word form document itself, but that is where I am stuck...
The following is demo code that shows how to access an embedded Excel chart.
Note that the Name (Shapes([indexValue])) of your chart Shape is probably different than in this code. You'll need to check and change that assignment. Also, your chart may be an InlineShape rather than a Shape, so you may need to adjust that bit, as well.
This code checks whether the Shape is actually a chart. If it is, the Chart object is accessed as well as its data sheet. Via that, it's possible to get the actual workbook, the worksheets, even the Excel application if you should need it.
Sub EditChartData()
Dim doc As Word.Document
Dim shp As Word.Shape
Dim cht As Word.Chart
Dim wb As Excel.Workbook, ws As Excel.Worksheet, xlApp As Excel.Application
Set doc = ActiveDocument
Set shp = doc.Shapes("MyChart")
If shp.HasChart Then
Set cht = shp.Chart
cht.ChartData.Activate
Set wb = cht.ChartData.Workbook
Set xlApp = wb.Application
Set ws = wb.ActiveSheet
Debug.Print ws.Cells(1, 2).Value2
End If
Set ws = Nothing
Set wb = Nothing
Set cht = Nothing
Set xlApp = Nothing
End Sub

Having troubles creating and formatting Word tables from Excel VBA

I'm new to MS Word VBA and am having troubles with manipulating Word documents from Excel.
The Biggest problem so far is: codes that work in Word VBA just don't work in Excel. Very strange and frustrating.
Below are the codes:
Sub abc()
Dim MSWordApp As Object, MSWordDoc As Object
Set MSWordApp = CreateObject("Word.Application")
Set MSWordDoc = MSWordApp.Documents.Add
MSWordApp.Visible = True
With MSWordDoc
With .PageSetup
.TopMargin = Application.CentimetersToPoints(0.51)
.BottomMargin = Application.CentimetersToPoints(0.51)
.LeftMargin = Application.CentimetersToPoints(0.51)
.RightMargin = Application.CentimetersToPoints(0.51)
End With
.Tables.Add Range:=.Range(0, 0), NumRows:=3, NumColumns:=2
With .Tables(1)
.Rows.Alignment = wdAlignRowCenter
.Rows.HeightRule = wdRowHeightExactly
.Rows.Height = Application.CentimetersToPoints(9.55)
.Columns.PreferredWidthType = wdPreferredWidthPoints
.Columns.PreferredWidth = Application.CentimetersToPoints(9.9)
End With
End With
MSWordApp.Activate
Set MSWordApp = Nothing
Set MSWordDoc = Nothing
End Sub
These codes work perfectly in MS Word (Of course I've changed the names of object etc when I use them in MS Word).
However, weird things happen in Excel:
1) ".Rows.Alignment = wdAlignRowCenter" just don't work at all. The Rows.Alignment of the Word table just remains as default.
2) ".Columns.PreferredWidthType = wdPreferredWidthPoints" causes error in Excel. It works fine in Word; though in Excel, an empty error msg will pop up when every time I call this property. Have no idea why...
When controlling Microsoft Word from Excel VBA, you need to add a reference to the Microsoft Word Object Library. To do so, make sure you are on your module in the VBA window, and then click Tools then References.... In the popup, scroll down to find "Microsoft Word XX.X Object Library". The version # will vary based on what you have installed.
If it doesn't show in the list, you can find it on your hard drive, by clicking "Browse..." and navigating to the program files folder where MS Word is installed, then selecting the file called "MSWORD.OLB".
Since your code is written for use with late binding, you should NOT be adding a reference to Word. Instead, you need to either define or replace the Word constants you're using. For example, instead of:
.Rows.Alignment = wdAlignRowCenter
.Rows.HeightRule = wdRowHeightExactly
you could use:
.Rows.Alignment = 1 '1=wdAlignRowCenter
.Rows.HeightRule = 2 '2=wdRowHeightExactly
Alternatively, after:
Dim MSWordApp As Object, MSWordDoc As Object
you would insert:
Const wdAlignRowCenter as Long = 1: Const wdRowHeightExactly as Long = 2
Otherwise, if you're going to set a reference to Word, you should make your code consistent with early binding throughout. For example, instead of:
Dim MSWordApp As Object, MSWordDoc As Object
Set MSWordApp = CreateObject("Word.Application")
Set MSWordDoc = MSWordApp.Documents.Add
you might use:
Dim MSWordApp As New Word.Application, MSWordDoc As Word.Document
Set MSWordDoc = MSWordApp.Documents.Add

Use Excel-VBA to create and Insert String/Text AND Image to Word Document table-cell

I tried since more days to create a Word Document with Excel-VBA
Step by Step:
first: create Word-Document and add a Table (Mailing-Label)
second: fill sometext into some cells. Works great!
Now my Problem:
at last, i want to append an Picture in the cell.
My Problem is, the Image RANGE clear the old text.
And i don't know, how to set the Image and the text at the end of the Loop.
My code
oDoc.Tables(1).Cell(zeile, spalte).Range.Text = "some string"
oDoc.Tables(1).Cell(zeile, spalte).Range.InlineShapes.AddPicture path_to_image
The way to understand what's happening is to think about how this would work if you were doing this manually, working with a selection. When you assign text to a Range that's like typing it in, as you'd expect. The second line of code, inserting the image, is like selecting the entire cell (in this case) then inserting the image: it replaces what's in the Range. When working manually, if you had selected the entire cell, you'd press Right Arrow or click at the end to put the focus after what had been typed.
The same principle applies when using a Range object: it needs to collapse in order to add something to it.
The following code example demonstrates this. It also highlights how the code can be made more efficient by assigning the table and the target range to objects.
Dim tbl As Word.Table 'or As Object if using late-binding
Dim rng As Word.Range 'or As Object if using late-binding
Dim chrCount As Long
Set tbl = oDoc.Tables(1)
Set rng = tbl.Cell(zeile, spalte).Range
rng.Text = "test"
chrCount = rng.Characters.Count
'Get the end of the cell content
Set rng = rng.Characters(chrCount - 1)
rng.Collapse wdCollapseEnd
rng.InlineShapes.AddPicture path_to_image
May be something like
Sub Test()
Dim Wrd As Word.Application
Dim oDoc As Word.Document
Set Wrd = CreateObject("Word.Application")
Wrd.Visible = True
Set oDoc = Wrd.Documents.Add
oDoc.Tables.Add oDoc.Range, 3, 3
zeile = 2
spalte = 2
path_to_image = "C:\Users\user\Desktop\Pull2.jpg"
oDoc.Tables(1).Cell(zeile, spalte).Range.Select
With Wrd.Selection
.TypeText Text:="some string"
.InlineShapes.AddPicture path_to_image
End With
End Sub

Text after table in Word using VBA codes

I create a Word document using VBA codes and transfer data from Excel to a table I create in the Word document.
I get an error starting a new line/paragraph after the table.
My code selects the whole table but does not start new text after the table, so later content is being added to cell(1,1) in the table.
I am just showing you the structure of my codes and I get an error at the Selection.Collapse line of code.
run time error 438, object doesn't support this property or method.
Sub Word_Report()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
With objWord.Selection
Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
myTable.Borders.Enable = True
''' my table contents'''
end with
'start new line after table
objDoc.Range.InsertAfter Chr(13) & "Hello"
.Font.Size = 11
.BoldRun
End sub
Edited
Try the following:
Sub Word_Report()
Dim objWord As Object
Dim objDoc As Object
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set objDoc = objWord.Documents.Add()
With objWord.Selection
Set myTable = objDoc.Tables.Add(Range:=objWord.Selection.Range, NumRows:=7, NumColumns:=3)
myTable.Borders.Enable = True
''' my table contents'''
End With
'start new line after table
objDoc.Range.InsertAfter Chr(13) & "Hello"
End Sub
Use .Range instead of Selection
To insert text immediately following at table, you have to set the range to the table then collapse the range. Insert your table, flow all your data into it, format the table.
When you've got it how you want it, use code like this where h1 is a Word.Range and objTemplate is a Word.Document object:
Set h1 = objTemplate.Tables(TableNum).Range
h1.Collapse Direction:=wdCollapseEnd

Resources