Search code examples
vbamacosms-wordnon-english

How do I delete paragraphs of a certain language?


I wish to delete Simplified Chinese text in a document with both English and Chinese. The documents don't have any set pattern for which paragraphs are in which language.

I tried a few versions of code that search by paragraph and by language.

Sub DeleteCN()
    iParCount = ActiveDocument.Paragraphs.Count
    For J = 1 To iParCount
        sMyPar = ActiveDocument.Paragraphs(J).Range.Text
        If sMyPar.WdLanguageID = wdSimplifiedChinese Then
            sMyPar.Delete
        End If
    Next J
End Sub

The error I get with this latest attempt is that an object is required on the If line.


Solution

  • You have a few issues with your code.

    1) The most serious is you must reverse your loop. The loop must be reversed because as you delete a paragraph the number of paragraphs will dynamically change and then future paragraphs will no longer exist.

    2) The rest are syntax errors, you can see where the syntax has been updated in the code. If you declare your variables it will be easier to know the correct syntax.

    Sub DeleteCN()
    
    Dim iParaCount As Integer
    Dim para As Paragraph
    
    iParaCount = ActiveDocument.Paragraphs.Count
    
    For J = iParaCount To 1 Step -1
        Set para = ActiveDocument.Paragraphs(J)
        If para.Range.LanguageID = wdSimplifiedChinese Then
            para.Range.Delete
        End If
    Next J
    
    End Sub
    

    Hope this helps.