The program below will look for a table called "Financial Data" and if it is found it will set the Table.Width property to 20%
Sub MyProgram()
'if SetTableWidth is false, then go to errHandler1
If Not SetTableWidth("Financial Data", 20) _
Then GoTo errHandler1
'Remainder of program code goes here.
Exit Sub
errHandler1:
'Notify user of faulure.
MsgBox "MyProgram has failed and is quitting...", _
vbCritical, "Program Failure"
End Sub
The function below will attempt to set the table width. It will return false if it fails.
Function SetTableWidth(ByVal strTitle As String, _
ByVal intWidth As Integer) As Boolean
Dim intTableNumber As Integer
Dim strResult As String
On Error GoTo errHandler1
'settablewidth = false until it reaches
'the end of function and is changed.
SetTableWidth = False
'Try to get item().
intTableNumber = GetTableItemNumber(strTitle)
Set objTable = ActiveDocument.all.tags("table"). _
Item(intTableNumber)
objTable.Style.Width = intWidth & "%"
'Set to true upon successfully getting here.
SetTableWidth = True
Exit Function
errHandler1:
'Set failure value to false
SetTableWidth = False
'Prompt user to retry or cancel.
strResult = MsgBox("Failed to set table width", _
vbRetryCancel, "Function Failure")
If strResult = 4 Then
Call SetTableWidth(strTitle, intWidth)
End If
End Function
The function call to GetTableItemNumber at about line 12 of the above function will call the function below.
Function GetTableItemNumber( _
ByVal strTitle As String) As Integer
On Error GoTo errHandler1
Dim i As Integer
Dim strResult As String
'if the number of tables is greater than 0
If Application.ActiveDocument.all. _
tags("table").Length > 0 Then
'Loop through each table.
For i = 0 To Application.ActiveDocument.all. _
tags("table").Length - 1
'Make it case non-sensitive.
If UCase(Application.ActiveDocument.all. _
tags("table").Item(i).Title) = Ucase(strTitle) Then
'Set GetTableItemNumber and exit.
GetTableItemNumber = i
Exit Function
End If
Next i
End If
'If program gets to this point then it has failed
'and should continue to errHandler1 next.
errHandler1:
'Set failure value to -1
GetTableItemNumber = -1
'Prompt user to retry or cancel.
strResult = MsgBox("Failed to find table " & _
strTitle, vbRetryCancel, "Function Failure")
If strResult = 4 Then
Call GetTableItemNumber(strTitle)
End If
End Function