VBA代码可在光标处选择表,避免在光标处没有表时发生崩溃

时间:2019-01-16 17:40:27

标签: vba ms-word

我有以下VBA宏,它可以在光标位置选择一个表,对表进行格式化并对文本进行格式化。

当光标不在表中时,我想避免它崩溃(运行时错误),而是显示诸如“选择表优先”之类的消息。

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

3 个答案:

答案 0 :(得分:1)

这可以通过计算当前选择中的表数来完成。如果不存在,则为零。在下面的代码示例中,如果表数为零,则会显示一条消息,但是当然可以将其删除。

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

答案 1 :(得分:0)

最好的方法是完全删除Selection.Select元素,因为您无需使用它们来与文档中的任何内容进行交互。但是,由于我对您的工作并不了解,因此应该可以满足您的需求:

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

答案 2 :(得分:0)

尝试:

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