Step through a word table selection with VBA - vba

I've been trying to write a Macro that changes some formatting in big tables in Word for me. I tried to find this information, but as soon as there are tables, the information is for excel.
So the situation I got is this, I got a table with 6 columns. The first two columns will get selected, the Macro started. Now I'd like it to read the first cell of the selection from the top left, then I do some manipulation/calculations with it, then I'd like to write back the manipulated data, move on to the cell to the right, read the data, manipulate it, write back something and then do so till the end of the Selection.
Can someone help me with a code skeleton? That would be awesome!

Here's a possible skeleton, it loops through columns 1 and 2 of a preexisting table.
Sub TestTable()
Dim wordApp As Word.Application
Dim docDocument As Word.Document
Dim tblTable As Word.Table
Dim c As Word.Cell
Dim sString As String
Dim iColumnNumber As Integer
Set wordApp = CreateObject("Word.Application")
Set docDocument = wordApp.Documents.Open("<location of your document e.g. C:\MyDoc.doc>")
Set tblTable = docDocument.Tables(1)
For iColumnNumber = 1 To 2
For Each c In tblTable.Columns(1).Cells
sString = c.Range.Text
'Do something
Next c
Next iColumnNumber
'wordApp.Visible = True
Set tblTable = Nothing
Set docDocument = Nothing
Set wordApp = Nothing
End Sub

Related

Add not replace content in Word Content Control using VBA

I am trying to generate multiple Word documents which have content controls that are populated from an Excel file. The second content control needs to be populated with a list which varies in length.
How do I add each value to the content control instead of replacing the current value? I am currently using Rich Text Content Controls.
Here is what I have so far:
Sub CreateCoverLetters()
Dim objWord As Word.Application
Dim wDoc As Word.Document
Dim Rows As Integer
Set objWord = CreateObject(Class:="Word.Application")
objWord.Visible = True
Set wDoc = objWord.Documents.Open(*insert filepath*)
objWord.Activate
wDoc.ContentControls(1).Range.Text = Worksheets("Lists").Range("A2").Value
Rows = Worksheets("Lists").Range("A3", Range("A3").End(xlDown)).Rows.Count
r = 3
For i = 1 To Rows
wDoc.ContentControls(2).Range.Text = Worksheets("Lists").Cells(r, 1).Value
r = r + 1
Next
wDoc.SaveAs (*insert filepath*)
End Sub
Any help much appreciated!
Solved it as follows:
Sub CreateCoverLetters()
Dim objWord As Word.Application
Dim wDoc As Word.Document
Dim Rows As Integer
Dim Content As String
Set objWord = CreateObject(Class:="Word.Application")
objWord.Visible = True
Set wDoc = objWord.Documents.Open(*insert filepath*)
objWord.Activate
wDoc.ContentControls(1).Range.Text = Worksheets("Lists").Range("A2").Value
Rows = Worksheets("Lists").Range("A3", Range("A3").End(xlDown)).Rows.Count
r = 3
For i = 1 To Rows
Content = Content & "- " & Worksheets("Lists").Cells(r, 1).Value & vbNewLine
r = r + 1
Next
wDoc.ContentControls(2).Range.Text = Content
wDoc.SaveAs (*insert filepath*)
End Sub
The approach in user's answer works if the content can 1) be concatenated in a single string and 2) none of the elements require special formatting. This would also be the fastest approach.
If for any reason this process is not possible, then the way to "append" content without replacing goes something like in the code snippet that follows.
Notice how Range and ContentControl objects are declared and instantiated, especially the Range object. This makes it much easier to pick up the "target" at a later point in the code. Also, a Range object can be collapsed (think of it like pressing the right-arrow to make a selection a blinking cursor): this makes it possible to append content and work with that new content (format it, for example). Word also has a Range.InsertAfter method which can be used if the new content does not have to be manipulated in any special way.
Dim cc as Object ' Word.ContentControl
Dim rngCC as Object 'Word.Range
Set cc = wDoc.ContentControls(1).Range
Set rngCC = cc.Range
rngCC.Text = Worksheets("Lists").Range("A2").Value
'Add something at a later point
rngCC.Collapse wdCollapseEnd
rngCC.Text = " New material at the end of the content control."

Get Word bookmark index to replace image inside bookmark from Excel

This question is related with a previous one.
I have an open Word document with a bunch of bookmarks, each with an inline image of an Excel table previously exported from Excel.
Now, I need to update the tables in the Word document as they have changed in Excel.
The way I'm doing this is matching the table names in Excel with the bookmark names in Word. If they are equal than I want to replace the existing images in Word by the current ones.
This is my code so far:
Option Explicit
Sub substituir()
Dim Mark As String
Dim Rng As Range
Dim ShpRng As Range
Dim WordApp As Object
Dim DocumentoDestino As Object
Dim folha As Worksheet
Dim tabela As ListObject
Dim nomeTabela As String
Set WordApp = GetObject(class:="Word.Application")
Set DocumentoDestino = WordApp.ActiveDocument
For Each folha In ThisWorkbook.Worksheets
If folha.Visible Then
'loop all excel tables
For Each tabela In folha.ListObjects
tabela.Name = Replace(tabela.Name, " ", "")
Mark = CStr(tabela.Name)
With ActiveDocument
If .Bookmarks.Exists(Mark) Then
Set Rng = .Bookmarks(Mark).Range ' returns runtime error 13: Type mismatch, I guess it is because .Bookmarks expects the bookmark index instead of the name.
If Rng.InlineShapes.Count Then
Set ShpRng = Rng.InlineShapes(1).Range
With ShpRng
Debug.Print .Start, .End
ShpRng.Delete
End With
End If
End If
End With
Next tabela
End If
Next folha
End Sub
The code seems ok, except for the line marked above that returns runtime error 13, is there any way to get to the bookmark index instead of the name or another way to fix the issue?
Thanks in advance!
The problem is from the Range object. There is such an object in Excel as well as in Word. Since you are running Excel, both Rng and ShpRng are declared as Excel ranges implicitly. Declare them as Word.Range.
Quite generally, be more careful with your use of variables. You perfectly declared Set DocumentoDestino = WordApp.ActiveDocument, but then you proceed with
With ActiveDocument
If .Bookmarks.Exists(Mark) Then
In Excel, there is no ActiveDocument. Perhaps that is why Excel correctly divines your intention to refer to DocumentoDestino. However, if you don't keep tight control instances are likely to arise - whenever you least expect them, of course - when Excel makes the wrong guess.

Exporting excel worksheet into ms access table

How can I import an excel worksheet into an MS Access table every time new data is added to the worksheet? Meaning every time I update my excel worksheet it would automatically update the ms access table?
I searched the internet and it seems there are several ways that it can be done, however I can't find a method that does exactly what I want. What I have so far isn't working nor does it do what I want it to do in the end. However, it is a start.
As I said I want vba to continuously update my access table through the excel worksheet. Right now the code isn't working. It keeps saying "path not found."
I tried debugging, but I haven't been able to figure out what was wrong with the path. This is what I have so far. Any suggestions on how to fix my code and or any suggestions for an easier way?
Sub ExportToAccess()
Dim oSelect As Range, i As Long, j As Integer, sPath As String
Sheet1.Activate
Set oSelect = Application.InputBox("Range", , Range("A1").CurrentRegion.Address, , , , , 8)
Dim oDAO As DAO.DBEngine, oDB As DAO.Database, oRS As DAO.Recordset
ChDir ActiveWorkbook.Path
sPath = Application.GetOpenFilename("Access * test.accdb\")
If sPath = "False" Then Exit Sub
Set oDAO = New DAO.DBEngine
Set oDB = oDAO.OpenDatabase(sPath)
Set oRS = oDB.OpenRecordset("ImportedData")
For i = 2 To oSelect.Rows.Count
oRS.AddNew
For j = 1 To oSelect.Columns.Count
oRS.Fields(j) = oSelect.Cells(i, j)
Next j
oRS.Update
Next i
oDB.Close
If MsgBox("Open the table?", vbYesNo) = vbYes Then
Dim oApp As Access.Application
Set oApp = New Access.Application
oApp.Visible = True
oApp.OpenCurrentDatabase sPath
oApp.DoCmd.OpenTable "ImportedData", acViewNormal, acReadOnly
oApp.DoCmd.GoToRecord , , acLast
DoEvents
End If
End Sub
Problem solved:
Though the method I used to solve my problem worked for me it might not be what most people would be expecting when seeing this post, however I still think it could be useful to some. Even though the solution I came up with is very simple. Instead of directly writing some code to transfer the data in my worksheet to an access table I simply had my vba code copy and paste the data that was entered into worksheet 1 then paste it into worksheet 2, then I linked worksheet 2 to an access table using the external data import function in access.

vba: Offset doesn't work from Word script in Excel doc

I have a Word document that should open an Excel document, find the first empty cell in a range and start filling some cells with information. Herefore I'd like to use Offset, but for some reason it gives an error with Offset. Here's the relevant part of the code:
Sub ExcelDoc()
Dim XLapp As Object
Dim objExcelDoc As Object
Dim objOverzicht As Object
Dim c As Range
'Set objOverzicht
Set objOverzicht = ActiveDocument
'Set XLapp and objExcelDoc
Set XLapp = CreateObject("Excel.Application")
XLapp.Visible = False
Set objExcelDoc = XLapp.Documents.Open("C:\Document.xlsm")
'Set c
Set c = objExcelDoc.Sheets("Overzicht").Range("B3")
Do
Set c = c.Offset(1, 0)
Loop Until c = ""
When I run the code, it marks ".Offset" and displays the message "Compile error: Method or data member not found". What am I doing wrong here?
Many thanks in advance for looking into this!
Word itself has a "Range" object, so when you declare Dim c As Range c is created as Word.Range object, which has no Offset property. So you have 2 ways of solving the problem:
Just declare c as Variant: Dim c as Variant
Make an MS Excel reference and declare variable with it:
2.1 In VBA Editor go to Tools->References and turn on "Microsoft Excel XX.X Object Library"
2.2 Declare variable with reference: Dim c as Excel.Range

Visual Basic - Select Random Excel Sheet and Random Cell

It has been a while since I've coded in Visual Basic, so I forgot much of what I knew when working with MS Excel. I am actually coding within the developer tab of MS Excel 2007.
I have an existing workbook that contains a sheet called "MySheet". In this sheet is a range of cells with text values, and the cells rangefrom A1:A10. I would like to click a button and select the text from any random cell within this range. The text would then be displayed in a message box. Here is what I have so far. This definitely doesn't work though. Any help please? Thanks!
Private Sub myButton_Click()
Dim xl As New Excel.Application
Dim xlsheet As Excel.Worksheet
Dim xlwbook As Excel.Workbook
Dim myCell As Range
Dim rndText As String
Dim rndIndex as Integer
rndIndex = **random number...not sure how**
rndText = ""
xlsheet = xl.Workbook.Sheets("MySheet")
myCell = xlsheet.Cells(rndIndex, 1)
rndText = myCell.Value
MsgBox (rndText)
End Sub
You're definitely on the right track. To get a random number in .NET, here's the way to do it:
Dim rand = new Random()
rndIndex = rand.Next()
'Or you can do this and set a minimum and maximum value for the random number
rndIndex = rand.Next(0, 100)