Jo Pedder
Jo Pedder

Reputation: 113

VBA code to select table at cursor which avoids a crash when there is no table at the cursor

I have the following VBA macro which selects a table at the cursor point, formats the table and formats the text.

I want to avoid it crashing (runtime error) when the cursor is not in a table and instead put up a message like "Select Table First".

Sub FormatTable(control As IRibbonControl)
'
' FormatTable Macro
'

Selection.Tables(1).Select
Selection.Tables(1).Style = "Prime Table 1"
Selection.Style = ActiveDocument.Styles("Normal")
End Sub

Upvotes: 1

Views: 167

Answers (3)

macropod
macropod

Reputation: 13505

Try:

Sub FormatTable(control As IRibbonControl)
With Selection
  If .Information(wdWithInTable) = True Then
    .Tables(1).Style = "Prime Table 1"
    .Style = "Normal"
  Else
    MsgBox "There's no table at the current selection."
  End If
End With
End Sub

Upvotes: 0

Cindy Meister
Cindy Meister

Reputation: 25663

This can be done by counting the number of tables in the current selection. If there's none, it will be zero. In the code sample, below, if there are zero tables, a message is shown, but this can, of course, be removed.

Sub FormatTable(control As IRibbonControl)
'
' FormatTable Macro
'

  If Selection.Tables.Count > 0 Then
    Selection.Tables(1).Select
    Selection.Tables(1).Style = "Prime Table 1"
    Selection.Style = ActiveDocument.Styles("Normal")
  Else
    MsgBox "There's no table at the current selection."
  End If
End Sub

Upvotes: 1

Dave
Dave

Reputation: 4356

The best method would involve removing the Selection and .Select elements entirely as you don't need to use them to interact with anything on your document. However as I don't know enough about what you're doing, this should work for your needs:

Sub FormatTable(control As IRibbonControl)
'
' FormatTable Macro
'
On Error Resume Next ' allow code to progress even if an error occurs
Selection.Tables(1).Select
If Err.Number <> 0 Then Goto ErrHandler    ' Detect an error and step out to handle it
Selection.Tables(1).Style = "Prime Table 1"
Selection.Style = ActiveDocument.Styles("Normal")

On Error Goto 0 'switch off the On Error Resume Next as you really want to limit its use

ErrHandler:
MsgBox "Please Select a Table First"
End Sub

Upvotes: 0

Related Questions