0

我在 Word VBA 中编写了以下代码,它可以工作。

Dim para As Paragraph
Dim nextPara As Paragraph
For Each para In ActiveDocument.Paragraphs
    If para.Style = CMB1.Value Then
        Set nextPara = para.Next
        If nextPara.Style = CMB2.Value Then
            If Not nextPara Is Nothing Then
                para.Style = CMB3.Value
                nextPara.Style = CMB4.Value
            End If
        End If
    End If
Next

我将该代码转换为 VSTO VB.NET:

    Dim para As Word.Paragraph
    Dim nextPara As Word.Paragraph

    For Each para In activeDoc.Paragraphs
        If para.Style = cmbStyle1.SelectedItem.ToString Then
            nextPara = para.Next
            If nextPara.Style = cmbStyle2.SelectedItem.ToString Then
                If Not nextPara Is Nothing Then
                    para.Style = cmbStyle3.SelectedItem.ToString
                    nextPara.Style = cmbStyle4.SelectedItem.ToString
                End If
            End If
        End If
    Next

但是当我运行时,在以下行中,它给出了一个错误。

如果 Para.Style = cmbStyle1.SelectedItem.ToString 那么

我应该怎么办?

4

2 回答 2

0

有时,使用 Word PIA 可能与 VBA 不同。当您使用 VB.NET 时不是很多,但有时会有点......

为了获得样式的名称,您首先需要一个 Style 对象。例如

    Dim para As Word.Paragraph = Globals.ThisAddIn.Application.Selection.Range.Paragraphs(1)
    Dim styl As Word.Style = para.Range.Style
    System.Diagnostics.Debug.Print(styl.NameLocal)

所以你的代码需要类似于下面的代码。请注意,无需创建 Style 对象即可样式分配给 Range。仅在获取样式的属性时。

Dim para As Word.Paragraph
Dim nextPara As Word.Paragraph
Dim paraStyle as Word.Style
Dim paraStyleNext as Word.Style

For Each para In activeDoc.Paragraphs
    paraStyle = para.Style
    If paraStyle.NameLocal = cmbStyle1.SelectedItem.ToString Then
        nextPara = para.Next
        paraStyleNext = nextPara.Style
        If paraStyleNext.NameLocal = cmbStyle2.SelectedItem.ToString Then
            If Not nextPara Is Nothing Then
                para.Style = cmbStyle3.SelectedItem.ToString
                nextPara.Style = cmbStyle4.SelectedItem.ToString
            End If
        End If
    End If
Next
于 2018-08-16T15:37:48.537 回答
0

Word 中的Paragraph.StyleProperty 是该WdBuiltinStyle类型的 Variant。您必须引用字符串Paragraph.Style.NameLocal

例子:

If para.Style.NameLocal = cmbStyle1.SelectedItem.ToString Then

确保在所有过程中都包含错误捕获。这是 .NET 的示例

于 2018-08-16T00:34:37.753 回答