我想在选择的特定段落中有多个单词时生成一个消息框,并在其中显示第二个单词。如果只有一个单词,则应显示空消息框。下面提供的是我生成的代码。有没有替代方法呢?
Sub Second()
Dim oPara As Paragraph
Dim Fi As String
Dim First As String
For Each oPara In Selection.Paragraphs
Fi = oPara.Range.Text
Dim arr() As String
arr = VBA.Split(Fi, " ")
First = arr(1)
Next
MsgBox First
End Sub
答案 0 :(得分:1)
通过这种方式,您可以处理索引超出范围的错误,并可以选择多个段落运行。
Sub Second()
Dim oPara As Paragraph
Dim Fi As String
Dim First As String
For Each oPara In Selection.Paragraphs
Fi = oPara.Range.Text
'ignore empty paragraphs
If Len(Fi) <> 1 Then
Dim arr() As String
arr = VBA.Split(Fi, " ")
On Error GoTo errHandler
First = arr(1)
GoTo regular
errHandler:
First = ""
regular:
MsgBox First
End If
Next
End Sub