检查样式名称或获取样式名称 VSTO Word VB.NET

Check style name or get style name VSTO Word VB.NET

我在 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

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

If Para.Style = cmbStyle1.SelectedItem.ToString Then

我该怎么办?

Paragraph.Style Property in Word is a Variant of the WdBuiltinStyle type. You'll have to reference the string Paragraph.Style.NameLocal.

示例:

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

Be sure to include error trapping in all your procedures. Here is an example for .NET

使用 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 对象即可将样式分配 到范围。仅在获取样式的属性时。

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