简体   繁体   中英

Problem when running for, next loop with if statement

I am trying to use a for next loop with an if then statement in Word VBA. The purpose of the code is that if the paragraph of the Word document is not empty, it will select the text and copy it and paste it in a new Word document. If the paragraph is empty, it will just go to the next line.

I have tried running the code and each time, it can only select the first paragraph in the whole Word document and I am not sure on how to let the code run and go on to the next paragraph to create a loop.

   Sub selectparawithtext()
    
    Dim opara As Paragraphs
    Dim x As Integer 
    
    For x = 1 To 24
    
    If Paragraphs <> "" Then 

      Selection.Expand wdParagraph
      Selection.Copy 
      Documents.Add wdNewBlankDocument
      Selection.PasteAndFormat (wdFormatOriginalFormatting)
    
    Else
      
      Selection.MoveDown Unit:=wdLine, Count:=1

    End If 
    Next 

    End Sub

You have two problems.

  1. You don't understand the Word object model.
  2. You have assumed that paragraphs with no visible text have a null content ("") which is incorrect.

To resolve 1 you need to iterate over the paragraphs in the story range that you wish to work with.

Dim myPara As Paragraph
For Each myPara In ActiveDocument.StoryRanges(wdMainTextStory).Paragraphs
    <your code>
Next

There are shortcuts to paragraphs in the body text of a document (eg .contents.paragraphs, or just .paragraphs but it is better to understand that word documents consist of a number of story ranges and to specify the story range with which you wish to work).

The second point is that word paragraphs are terminated by a paragraph marker character which is part of the paragraph text. Thus paragraphs can never have a null value as they always have a minimum length of 1 character.

The text of a paragraph is part of the range object of a paragraph. Thus to access the text of paragraph x you would use

\<document qualifier>.\<storyrange qualifier>.paragraphs.item(x).range.text.

eg

ActiveDocument.StoryRanges(wdmaintextstory).paragraphs.item(x).range.text

Its worth noting that 'Item' is the default property of the paragraphs object hence why Paragraphs(x) and Paragraphs.Item(x) appear to give the same result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM