Home > Mobile >  How to grab a new line in Word by Excel VBA code
How to grab a new line in Word by Excel VBA code

Time:11-28

I have code that takes the contents of a Word file into a variable, so I parse the contents and handle it by VBA code. My question is: I'm currently scanning letters by a loop, but I don't know how to find a line break. Any help is appreciated Thank you This is the code I'm currently using

Sub open_word_find_text()

Dim book1 As Word.Application
Dim sheet1 As Word.Document
Set book1 = CreateObject("word.application")
book1.Visible = True

                GetFilePath = Application.GetOpenFilename   'Select a file'
                         Filename = Mid(GetFilePath, InStrRev(GetFilePath, "\")   1, 999):
                        FilePath = Mid(GetFilePath, 1, InStrRev(GetFilePath, Filename) - 2)
 find_text = InputBox("Type the text you are looking for:")
     
file = Dir(FilePath & "\")

               While (file <> "")  'loop over all the files in the folder
                  
                  If InStr(file, ".docx") > 0 Then
              
                      Filename = Mid(file, InStrRev(file, "\")   1, 999):
                      
                       Set sheet1 = book1.Documents.Open(FilePath & "\" & file)
                                                             
                            ff = sheet1.Content   'Save the contents of the file in a variable
                                  count_result = 0
                             For i = 1 To Len(ff)

                                  ff2 = Mid(ff, i, Len(find_text))
                                    
                                  If ff2 = find_text Then
                                    count_result = count_result   1                                  
                                      MsgBox "Number result: " & count_result & vbNewLine & Mid(ff, i - 150, i   200), vbOKCancel   vbMsgBoxRight   vbAbortRetryIgnore, Filename
                                  End If
                                    DoEvents
                             Next
b:
                  End If                   
                 sheet1.Close
                 file = Dir
                 DoEvents
              Wend
book1.Quit
MsgBox " end!"
End Sub

CodePudding user response:

I don't understand what you are trying to do, but the following will store the contents of the document in a string array by splitting on the vbCr-constant representing the line break:

Dim sLinesArr() As String
sLinesArr = Split(sheet1.Content.Text, vbCr)

The array can then be used in a loop:

Dim vLine As Variant

For Each vLine In sLinesArr
    MsgBox vLine
Next
  • Related