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

时间:2018-08-15 10:05:16

标签: vb.net ms-word vsto word-style

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

我该怎么办?

2 个答案:

答案 0 :(得分:0)

Word中的Paragraph.Style属性是WdBuiltinStyle类型的变体。您必须引用字符串Paragraph.Style.NameLocal

示例:

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

请确保在所有过程中都包括错误陷阱。 Here is an example for .NET

答案 1 :(得分: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)

因此,您的代码将需要类似于以下代码。请注意,不必为将分配样式分配给Range而创建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