I wrote the following code in Word VBA and it works.
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
I converted that code to 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
But when I run, in the following line, it gives an error.
If Para.Style = cmbStyle1.SelectedItem.ToString Then
What should I do?
Working with the Word PIAs can differ, sometimes, from VBA. Not a lot when you work with VB.NET, but sometimes a bit...
In order to get the style's name you first need a Style object. For example
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)
So your code would need to be something like the code that follows. Note that it's not necessary to create a Style object in order to assign a style to a Range. Only when getting the style's properties.
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