VB Script automate Microsoft Word Table Cell Content Replace Part of Text

Keith McElroy
Keith McElroy used Ask the Experts™
on
I have a couple hundred Microsoft Word Tables each with a cell with the following value
FY 2016
Actual

I need to increment the year and attempted this way which did not do anything:

dim newval
newval = "2017"
call replace(tbl.cell(row,2).range.text,"2016",newval)

Question:  How can I modify this code so that it replaces the 2016 with 2017?

If possible I wish to keep the original text and just replace the 2016.  
That way I do not loose the line break
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Ryan ChongSoftware Team Lead

Commented:
you can try:

Sub test()
    Dim oldval, newval, Row, Col
    Dim tbl As Table
    
    oldval = "2016"
    newval = "2017"
    Row = 1
    Col = 2
    
    Set tbl = ActiveDocument.Tables(1)
    If InStr(1, tbl.Cell(Row, Col).Range.Text, oldval, vbTextCompare) Then
        tbl.Cell(Row, Col).Range.Text = newval
    End If
End Sub

Open in new window

Top Expert 2016
Commented:
Hi,

pls try
Sub Macro()
  
    oldval = "2016"
    newval = "2017"
    Row = 1
    
    Set tbl = ActiveDocument.Tables(1)
    If InStr(1, tbl.Cell(Row, 2).Range.Text, oldval, vbTextCompare) Then
        res = Replace(tbl.Cell(Row, Col).Range.Text, oldval, newval)
        tbl.Cell(Row, Col).Range.Text = Left(res, Len(res) - 2)
    End If
End Sub

Open in new window

Regards

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial